DateUtils.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import time
  2. from datetime import date, datetime, timedelta
  3. import calendar
  4. from dateutil.relativedelta import relativedelta
  5. class DateUtils:
  6. """
  7. 时间相关函数封装
  8. """
  9. def __init__(self):
  10. self.today = datetime.strptime(datetime.today().strftime("%Y-%m-%d"), "%Y-%m-%d")
  11. self.daydelta = timedelta(days=1)
  12. self.now = datetime.now()
  13. def getDateLists(self, begin, end):
  14. """
  15. 返回一个时间列表
  16. """
  17. interval = self.getInterval(begin, end)
  18. return [self.getLastDays(begin, -x) for x in range(interval + 1)]
  19. def getTodayOrYestoday(self):
  20. """
  21. 如果当天零点 则返回昨天
  22. 否则返回今天
  23. :return:
  24. """
  25. if self.now.hour==0:
  26. return self.get_n_days(-1)
  27. else:
  28. return self.get_n_days(0)
  29. def getMonthLists(self, begin, end):
  30. begin_date = datetime.strptime(begin, "%Y-%m").date()
  31. end_date = datetime.strptime(end, '%Y-%m').date()
  32. temp = end_date
  33. month_list = []
  34. while temp >= begin_date:
  35. month_list.append(temp.strftime('%Y-%m'))
  36. temp = self.get_before_month(temp.year, temp.month, 1, 1)
  37. month_list.reverse()
  38. return month_list
  39. def getLastDays(self, begin, interval):
  40. """
  41. :param begin:
  42. :param interval: 正数是之前几天, 负数是之后几天
  43. :return:
  44. """
  45. start = datetime(int(begin[0:4]), int(begin[5:7]), int(begin[8:10]))
  46. delta = timedelta(days=1)
  47. if interval < 0:
  48. for _ in range(0, -interval):
  49. start = start + delta
  50. else:
  51. for _ in range(0, interval):
  52. start = start - delta
  53. return start.strftime("%Y-%m-%d")
  54. def get_n_month_ago_begin(self, begin, n):
  55. year = int(begin[:4])
  56. month = int(begin[5:7])
  57. if n > 0:
  58. for i in range(0, n):
  59. month -= 1
  60. if month == 0:
  61. month = 12
  62. year -= 1
  63. else:
  64. for i in range(0, -n):
  65. if month == 12:
  66. month = 0
  67. year += 1
  68. month += 1
  69. return date(year, month, 1).strftime('%Y-%m')
  70. def get_n_days(self, interval=0, flag=0):
  71. """
  72. 负数,过去的几天
  73. 正数,未来的几天
  74. :param interval:
  75. :param flag: 1 返回 timedelta
  76. :return:
  77. """
  78. start = self.today
  79. if interval < 0:
  80. for _ in range(0, -interval):
  81. start = start - self.daydelta
  82. else:
  83. for _ in range(0, interval):
  84. start = start + self.daydelta
  85. if flag == 1:
  86. return start
  87. else:
  88. return start.strftime("%Y-%m-%d")
  89. def getNow(self):
  90. """
  91. 获取当天时间
  92. :return: 当天时间的字符串
  93. """
  94. now = datetime.now()
  95. return now.strftime("%Y-%m-%d")
  96. def getWeek(self, begin):
  97. return datetime(int(begin[0:4]), int(begin[5:7]), int(begin[8:10])).strftime("%w")
  98. def get_today_before_month(self, n):
  99. """
  100. 获取之前n个月
  101. :param n:
  102. :return:
  103. """
  104. year = time.localtime()[0]
  105. month = time.localtime()[1]
  106. for i in range(0, n):
  107. month -= 1
  108. if month == 0:
  109. month = 12
  110. year -= 1
  111. return year, month
  112. def get_one_month_ago(self, flag=0):
  113. """
  114. 返回一个月前的时间, 默认返回格式化时间字符串
  115. flag 1 返回 datetime
  116. :param flag:
  117. :return:
  118. """
  119. x = self.today-relativedelta(months=1)
  120. if flag == 1:
  121. return x
  122. else:
  123. return x.strftime("%Y-%m-%d")
  124. def get_today_before_month_list(self, n=0):
  125. year = time.localtime()[0]
  126. month = time.localtime()[1]
  127. ret = []
  128. for i in range(0, n):
  129. month -= 1
  130. if month == 0:
  131. month = 12
  132. year -= 1
  133. if month >= 10:
  134. ret.append(str(year) + "-" + str(month) + "-" + "01")
  135. else:
  136. ret.append(str(year) + "-0" + str(month) + "-" + "01")
  137. return ret
  138. def get_before_month(self, year, month, day, n):
  139. for i in range(0, n):
  140. month -= 1
  141. if month == 0:
  142. month = 12
  143. year -= 1
  144. day = min(day, calendar.monthrange(year, month)[1])
  145. return date(year, month, day)
  146. def getInterval(self, begin, end):
  147. t1 = datetime(int(begin[0:4]), int(begin[5:7]), int(begin[8:10]))
  148. t2 = datetime(int(end[0:4]), int(end[5:7]), int(end[8:10]))
  149. return (t2 - t1).days
  150. def month_first_day(self, flag=False):
  151. """
  152. 返回当月第一天
  153. 若为1号,则返回上个月1号
  154. :param flag:
  155. :return:
  156. """
  157. if self.today.day == 1:
  158. # 如果当日是月初1号,则返回上月1号
  159. if self.today.month == 1:
  160. tmp = date(self.today.year - 1, 12, 1)
  161. else:
  162. tmp = date(self.today.year, self.today.month - 1, 1)
  163. else:
  164. tmp = date(self.today.year, self.today.month, 1)
  165. return tmp if flag else tmp.strftime("%Y-%m-%d")
  166. def get_today(self, flag=False):
  167. return self.today if flag else self.today.strftime("%Y-%m-%d")
  168. def get_n_pre_month_first_day(self, n, flag=False):
  169. """
  170. 获取 n 个月前第一天
  171. """
  172. r = self.get_before_month(self.today.year, self.today.month, 1, n)
  173. return r if flag else r.strftime("%Y-%m-%d")
  174. def get_n_month_ago(self, n, flag=0):
  175. d = self.get_before_month(self.today.year, self.today.month, self.today.day, n)
  176. return d.strftime("%Y-%m-%d") if flag == 0 else d
  177. def get_week_ago(self, flag=False):
  178. """
  179. :param: None
  180. :return: 7 days ago
  181. """
  182. tmp = (self.today - timedelta(days=7))
  183. return tmp if flag else tmp.strftime("%Y-%m-%d")
  184. def get_week_first_day(self, flag=False):
  185. """
  186. 返回当前天的一周开始
  187. :param flag:
  188. :return:
  189. """
  190. # print self.today.day
  191. if self.today.weekday() == 0:
  192. # 如果当天是周一,则返回上周一日期
  193. tmp = self.today - timedelta(days=7)
  194. else:
  195. tmp = self.today - timedelta(days=self.today.weekday())
  196. return tmp if flag else tmp.strftime("%Y-%m-%d")
  197. def get_one_day_ago(self, flag=False):
  198. """
  199. :param: None
  200. :return: 1 day ago
  201. """
  202. tmp = (self.today - timedelta(days=1))
  203. return tmp if flag else tmp.strftime("%Y-%m-%d")
  204. def get_start(self, s_start=date.today().strftime("%Y-%m-%d")):
  205. return datetime(int(s_start[0:4]), int(s_start[5:7]), int(s_start[8:10]))
  206. def get_n_hours_ago(self, n=1, flag = 0):
  207. """
  208. get n hous ago
  209. flag is True return datetime format
  210. default 1 hours ago
  211. if n > 0 :
  212. 过去时间
  213. else:
  214. 未来时间
  215. :param n:
  216. :return:
  217. """
  218. r = self.now - timedelta(hours=n)
  219. return r if flag else r.strftime("%Y-%m-%d %H:00:00")
  220. def get_n_minutes_ago(self, n=1, string=True):
  221. """
  222. get n minutes ago
  223. default 1 minutes ago
  224. if n > 0 :
  225. 过去时间
  226. else:
  227. 未来时间
  228. :param n:
  229. :return:
  230. """
  231. if string:
  232. return (self.now - timedelta(minutes=n)).strftime("%Y-%m-%d %H:%M")
  233. else:
  234. return self.now - timedelta(minutes=n)
  235. def get_n_pre_month_last_day(self, n=0, flag=False):
  236. """
  237. 获取 n 个月前的最后一天
  238. :param n:
  239. :param flag:
  240. :return:
  241. """
  242. r = self.get_before_month(self.today.year, self.today.month, 1, n)
  243. num = calendar.monthrange(r.year, r.month)[1]
  244. x = r.replace(day=num)
  245. return x if flag else x.strftime("%Y-%m-%d")
  246. @staticmethod
  247. def str_to_stamp(str):
  248. return int(time.mktime(time.strptime(str,'%Y-%m-%d')))
  249. if __name__ == "__main__":
  250. ut = DateUtils()
  251. end = ut.now.strftime('%Y-%m') + '-01 00:00:00'
  252. # begin = ut.get_n_month_ago_begin(ut.now.strftime('%Y-%m'), 1) + '-01 00:00:00'
  253. # print(ut.get_n_pre_month_first_day(0))
  254. # ut.today = date(2018, 1, 1)
  255. # print(ut.month_first_day())
  256. # a='2021-01-01 00:01:01'
  257. # b=datetime.strptime(a,'%Y-%m-%d %H:%M:%S')
  258. # print(b.hour)
  259. # print(ut.now.hour)