DateUtils.py 10 KB

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