LocalDateTimeUtil.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #!/usr/bin/python3.6
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright (C) 2022 #
  5. # @Time : 2022/3/26 16:20
  6. # @Author : ming
  7. # @Email : zhangdongming@asj6.wecom.work
  8. # @File : LocalDateTimeUtil.py
  9. # @Software: PyCharm
  10. import calendar
  11. import datetime
  12. import time
  13. from dateutil.relativedelta import relativedelta
  14. def get_cur_month():
  15. # 获取当前月
  16. return datetime.datetime.now().strftime("%Y-%m")
  17. def get_last_month_num(number=1):
  18. # 获取前几个月
  19. month_date = datetime.datetime.now().date() - relativedelta(months=number)
  20. return month_date.strftime("%Y-%m")
  21. def get_next_month(number=1):
  22. # 获取后几个月
  23. month_date = datetime.datetime.now().date() + relativedelta(months=number)
  24. return month_date.strftime("%Y-%m")
  25. def get_cur_month_start():
  26. # 获取当前月的第一天
  27. month_str = datetime.datetime.now().strftime('%Y-%m')
  28. return '{}-01'.format(month_str)
  29. def get_cur_month_end():
  30. # 获取当前月的最后一天
  31. """
  32. param: month_str 月份,2021-04
  33. """
  34. # return: 格式 %Y-%m-%d
  35. month_str = datetime.datetime.now().strftime('%Y-%m')
  36. year, month = int(month_str.split('-')[0]), int(month_str.split('-')[1])
  37. end = calendar.monthrange(year, month)[1]
  38. return '{}-{}-{}'.format(year, month, end)
  39. def get_last_month_start(month_str=None):
  40. # 获取上一个月的第一天
  41. """
  42. param: month_str 月份,2021-04
  43. """
  44. # return: 格式 %Y-%m-%d
  45. if not month_str:
  46. month_str = datetime.datetime.now().strftime('%Y-%m')
  47. year, month = int(month_str.split('-')[0]), int(month_str.split('-')[1])
  48. if month == 1:
  49. year -= 1
  50. month = 12
  51. else:
  52. month -= 1
  53. return '{}-{}-01'.format(year, month)
  54. def get_next_month_start(month_str=None):
  55. # 获取下一个月的第一天
  56. """
  57. param: month_str 月份,2021-04
  58. """
  59. # return: 格式 %Y-%m-%d
  60. if not month_str:
  61. month_str = datetime.datetime.now().strftime('%Y-%m')
  62. year, month = int(month_str.split('-')[0]), int(month_str.split('-')[1])
  63. if month == 12:
  64. year += 1
  65. month = 1
  66. else:
  67. month += 1
  68. return '{}-{}-01'.format(year, month)
  69. def get_last_month_end(month_str=None):
  70. # 获取上一个月的最后一天
  71. """
  72. param: month_str 月份,2021-04
  73. """
  74. # return: 格式 %Y-%m-%d
  75. if not month_str:
  76. month_str = datetime.datetime.now().strftime('%Y-%m')
  77. year, month = int(month_str.split('-')[0]), int(month_str.split('-')[1])
  78. if month == 1:
  79. year -= 1
  80. month = 12
  81. else:
  82. month -= 1
  83. end = calendar.monthrange(year, month)[1]
  84. return '{}-{}-{}'.format(year, month, end)
  85. def get_next_month_end(month_str=None):
  86. # 获取下一个月的最后一天
  87. """
  88. param: month_str 月份,2021-04
  89. """
  90. # return: 格式 %Y-%m-%d
  91. if not month_str:
  92. month_str = datetime.datetime.now().strftime('%Y-%m')
  93. year, month = int(month_str.split('-')[0]), int(month_str.split('-')[1])
  94. if month == 12:
  95. year += 1
  96. month = 1
  97. else:
  98. month += 1
  99. end = calendar.monthrange(year, month)[1]
  100. return '{}-{}-{}'.format(year, month, end)
  101. def get_last_first_date_and_last_date(n):
  102. """
  103. 获取前n周开始时间和结束时间,参数n:代表前n周
  104. """
  105. now = datetime.datetime.now()
  106. # 上周第一天和最后一天
  107. before_n_week_start = now - datetime.timedelta(days=now.weekday() + 7 * n, hours=now.hour, minutes=now.minute,
  108. seconds=now.second, microseconds=now.microsecond)
  109. # last_week_end = now - timedelta(days=now.weekday() + 1)
  110. before_n_week_end = before_n_week_start + datetime.timedelta(days=6, hours=23, minutes=59, seconds=59)
  111. return before_n_week_start, before_n_week_end
  112. def get_today_date(timestamp=False):
  113. """
  114. 返回当天开始时间和结束时间
  115. Args:
  116. timestamp 是否返回时间戳
  117. returns:
  118. zero_today ,last_today
  119. """
  120. now = datetime.datetime.now()
  121. zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
  122. microseconds=now.microsecond)
  123. last_today = zero_today + datetime.timedelta(hours=23, minutes=59, seconds=59)
  124. if timestamp:
  125. zero_today = int(time.mktime(zero_today.timetuple()))
  126. last_today = int(time.mktime(last_today.timetuple()))
  127. return zero_today, last_today
  128. return zero_today, last_today
  129. def get_last_week():
  130. """
  131. 获取前一周时间
  132. @return: last_week_date
  133. """
  134. today = datetime.date.today() # 1. 获取「今天」
  135. last_week = today - datetime.timedelta(days=7) # 2.获取7天前
  136. last_week_date = last_week.strftime("%Y-%m-%d %H:%M:%S")
  137. return last_week_date
  138. def get_last_month():
  139. """
  140. 获取前一个月时间
  141. returns:
  142. last_month_date
  143. """
  144. today = datetime.date.today() # 1. 获取「今天」
  145. last_month = today.replace(month=today.month - 1) # 2.获取前一个月
  146. last_month_date = last_month.strftime("%Y-%m-%d %H:%M:%S")
  147. return last_month_date
  148. def get_before_days_timestamp(timestamp, days=1):
  149. """
  150. 获取之前日期时间戳-秒级
  151. @param timestamp: 时间戳
  152. @param days: 天数
  153. @return: (timestamp - second * hour * days) 时间戳
  154. """
  155. if days:
  156. second = 3600
  157. hour = 24
  158. if days > 0:
  159. return timestamp - second * hour * days
  160. return 0
  161. def get_after_days_timestamp(timestamp, days=1):
  162. """
  163. 获取之后日期时间戳-秒级
  164. @param timestamp: 时间戳
  165. @param days: 天数
  166. @return: (timestamp + second * hour * days) 时间戳
  167. """
  168. if days:
  169. second = 3600
  170. hour = 24
  171. if days > 0:
  172. return timestamp + second * hour * days
  173. return 0
  174. def date_to_week(str_date):
  175. """
  176. 日期获取星期几
  177. @param str_date 日期 例:2022-03-03
  178. @return: int 1-7
  179. """
  180. if str_date:
  181. return datetime.datetime.strptime(str_date, "%Y-%m-%d").weekday() + 1
  182. return datetime.datetime.now().weekday() + 1
  183. def format_date_to_week(str_date, str_format):
  184. """
  185. 日期获取星期几
  186. @param str_format: %Y-%m-%d
  187. @param str_date 日期 例:2022-03-03
  188. @return: int 1-7
  189. """
  190. if str_date:
  191. return datetime.datetime.strptime(str_date, str_format).weekday() + 1
  192. return 0
  193. def get_start_and_end_time(date, str_format):
  194. """
  195. 根据日期获取当日开始and结束时间戳
  196. @param date: 日期 例:2022-03-07
  197. @param str_format: 格式 例:%Y-%m-%d
  198. @return: start_time,end_time
  199. """
  200. if date:
  201. today = datetime.datetime.strptime(date, str_format)
  202. day = today + datetime.timedelta(days=1)
  203. start_time = int(time.mktime(time.strptime(str(today.date()), '%Y-%m-%d')))
  204. end_time = int(time.mktime(time.strptime(str(day.date()), '%Y-%m-%d'))) - 1
  205. return start_time, end_time
  206. return 0
  207. def time_stamp_to_time(time_stamp, time_format):
  208. """
  209. 时间戳转时间
  210. @param time_stamp: 时间戳
  211. @param time_format: 时间格式 例%Y-%m-%d %H:%M:%S
  212. @return: 格式化后时间字符串
  213. """
  214. time_array = time.localtime(time_stamp)
  215. return time.strftime(time_format, time_array)
  216. def time_format_date(timestamp, tz):
  217. # 解析时区偏移量
  218. tz_hours, tz_minutes = map(int, tz.split(':'))
  219. # 将时间戳转换为 datetime 对象
  220. dt = datetime.datetime.fromtimestamp(timestamp)
  221. # 创建 timedelta 对象,表示时区偏移量
  222. tz_offset = datetime.timedelta(hours=tz_hours, minutes=tz_minutes)
  223. # 调整 datetime 对象的时区
  224. dt = dt + tz_offset
  225. # 格式化日期时间字符串
  226. formatted_date = dt.strftime('%Y-%m-%d %H:%M:%S')
  227. return formatted_date