date_util.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. __title__ = '操作时间的工具类'
  5. @Time : 2020/9/26 19:44
  6. @Author : Kenny-PC
  7. @Software: PyCharm
  8. # code is far away from bugs with the god animal protecting
  9. I love animals. They taste delicious.
  10. ┏┓ ┏┓
  11. ┏┛┻━━━┛┻┓
  12. ┃ ☃ ┃
  13. ┃ ┳┛ ┗┳ ┃
  14. ┃ ┻ ┃
  15. ┗━┓ ┏━┛
  16. ┃ ┗━━━┓
  17. ┃ 神兽保佑 ┣┓
  18. ┃ 永无BUG! ┏┛
  19. ┗┓┓┏━┳┓┏┛
  20. ┃┫┫ ┃┫┫
  21. ┗┻┛ ┗┻┛
  22. """
  23. import datetime
  24. import time
  25. from datetime import timedelta
  26. from dateutil.relativedelta import relativedelta
  27. # ==========================
  28. # ========== time ==========
  29. # ==========================
  30. def getDateLists(begin, end):
  31. """
  32. 返回一个时间列表
  33. """
  34. interval = getInterval(begin, end)
  35. return [getLastDays(begin, -x) for x in range(interval + 1)]
  36. def getInterval(begin, end):
  37. t1 = datetime.datetime(int(begin[0:4]), int(begin[5:7]), int(begin[8:10]))
  38. t2 = datetime.datetime(int(end[0:4]), int(end[5:7]), int(end[8:10]))
  39. return (t2 - t1).days
  40. def getLastDays( begin, interval):
  41. """
  42. :param begin:
  43. :param interval: 正数是之前几天, 负数是之后几天
  44. :return:
  45. """
  46. start =datetime.datetime(int(begin[0:4]), int(begin[5:7]), int(begin[8:10]))
  47. delta = timedelta(days=1)
  48. if interval < 0:
  49. for _ in range(0, -interval):
  50. start = start + delta
  51. else:
  52. for _ in range(0, interval):
  53. start = start - delta
  54. return start.strftime("%Y-%m-%d")
  55. def str_to_stamp(str):
  56. return int(time.mktime(time.strptime(str,'%Y-%m-%d')))
  57. def getLastMonthDay():
  58. """
  59. 获取上月第一天和最后一天
  60. @returen str"""
  61. today = datetime.date.today()
  62. last_day_of_last_month = datetime.date(today.year, today.month, 1) - datetime.timedelta(1)
  63. first_day_of_last_month = datetime.date(last_day_of_last_month.year, last_day_of_last_month.month, 1)
  64. return first_day_of_last_month, last_day_of_last_month
  65. def getCurrentMilliSecondTime():
  66. """
  67. description: 获取当前时间-毫秒级
  68. return: 1557730376981 -> str
  69. """
  70. timestamps = str(round(time.time() * 1000))
  71. return timestamps
  72. def getCurrentSecondTime():
  73. """
  74. description: 获取当前时间-秒级
  75. return: 1557730377 -> int
  76. """
  77. timestamps = int(time.time())
  78. return timestamps
  79. def getCurrentTimeTuple(times=time.time()):
  80. """
  81. description: 接受秒级时间戳并返回时间元组(与mktime(tuple)相反)
  82. times: 默认当前时间 可传second
  83. return: (tm_year=2019, tm_mon=5, tm_mday=13, tm_hour=10, tm_min=9, tm_sec=18, tm_wday=0, tm_yday=133, tm_isdst=0) -> tuple
  84. tips: time.localtime() 不传参则取当前时间
  85. """
  86. timestamps = time.localtime(times)
  87. return timestamps
  88. def getTimeByTuple(tupleTime=time.localtime()):
  89. """
  90. description: 接受时间元组并返回秒级时间戳(与localtime(sec)相反)
  91. tupleTime: 默认当前时间的元组 可通过time.localtime() or datetime.datetime.now().timetuple()获取
  92. return: 1557733061 -> str
  93. """
  94. timestamps = str(round(time.mktime(tupleTime)))
  95. return timestamps
  96. def getCurrentFormatTimeStr(times=time.time()):
  97. """
  98. description: 将指定时间元组格式化为字符串
  99. times: 默认当前时间 可传second
  100. return: 2019-05-13 15:00:47 -> str
  101. tips: %y 两位数的年份表示(00-99) %Y 四位数的年份表示(000-9999) %m 月份(01-12) %d 月内中的一天(0-31)
  102. %H 24小时制小时数(0-23) %I 12小时制小时数(01-12) %M 分钟数(00=59) %S 秒(00-59) %w 星期(0-6)
  103. """
  104. timestamps = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(times))
  105. return timestamps
  106. def getCurrentTimeTupleByFormatStr(time_str=str(datetime.datetime.now()).split(".")[0],
  107. format_type="%Y-%m-%d %H:%M:%S"):
  108. """
  109. description: 接受格式化字符串返回时间元组
  110. time_str: 格式化字符串 如:2019-05-13 15:00:47 默认当前时间
  111. format_type: 格式化规则 如:%Y-%m-%d %H:%M:%S 默认%Y-%m-%d %H:%M:%S
  112. return: (tm_year=2019, tm_mon=5, tm_mday=13, tm_hour=10, tm_min=9, tm_sec=18, tm_wday=0, tm_yday=133, tm_isdst=0) -> tuple
  113. """
  114. return time.strptime(time_str, format_type)
  115. def getCurrentTimeStr():
  116. """
  117. description: 获取当前时间的可读形式字符串
  118. return: Mon May 13 11:27:42 2019 -> str
  119. """
  120. return time.ctime()
  121. def getCurrentTimeStrByTuple(tupleTime=time.localtime()):
  122. """
  123. description: 获取指定时间的可读形式字符串
  124. tupleTime: 时间元组 可通过time.localtime() or datetime.datetime.now().timetuple()获取 默认当前时间的元组
  125. return: Mon May 13 11:27:42 2019 -> str
  126. """
  127. return time.asctime(tupleTime)
  128. def sleepTime():
  129. """
  130. description: 推迟调用线程的运行
  131. """
  132. for i in range(4):
  133. print(i)
  134. time.sleep(3)
  135. # ======================
  136. # ====== datetime ======
  137. # ======================
  138. def getNowDateTime():
  139. """
  140. description: 获取当前日期&时间
  141. return: 2019-05-13 14:41:15 -> str
  142. """
  143. timestamps = str(datetime.datetime.now()).split(".")[0]
  144. return timestamps
  145. def getNowTime():
  146. """
  147. description: 获取当前时间
  148. return: 14:41:15 -> str
  149. """
  150. timestamps = str(datetime.datetime.now().time()).split(".")[0]
  151. return timestamps
  152. def getTodayDate():
  153. """
  154. description: 获取当前日期
  155. return: 2019-05-13 -> str
  156. tipe: datetime.datetime.now().date()有相同效果
  157. """
  158. timestamps = str(datetime.date.today())
  159. return timestamps
  160. def getTimeDate(times=time.time()):
  161. """
  162. description: 获取指定时间戳的日期
  163. time: 秒 默认当前时间
  164. return: 2019-05-13 -> str
  165. tips: 一天86400秒
  166. """
  167. timestamps = str(datetime.date.fromtimestamp(round(times)))
  168. return timestamps
  169. def getAnyDateTime(day, hour=0, min=0, sec=0):
  170. """
  171. description: 获取距离现在时间的任意时间的日期&时间
  172. day: 天数 1代表当前时间+1天 -1代表当前时间-1天
  173. hour: 小时 2代表当前时间+2h -2代表当前时间-2h 默认=0
  174. min: 分钟 30代表当前时间+30min -30代表当前时间-30m 默认=0
  175. sec: 秒 120代表当前时间+120s -120代表当前时间-120s 默认=0
  176. return: 2019-05-15 15:37:41 -> str
  177. """
  178. return str(datetime.datetime.now() + datetime.timedelta(days=day, hours=hour, minutes=min, seconds=sec)).split(".")[
  179. 0]
  180. def getSecondsToDatetime(seconds=getCurrentSecondTime(), datetime_format="%Y-%m-%d %H:%M:%S"):
  181. """
  182. description: 秒/时间戳转日期字符串
  183. seconds: 时间戳 默认为当前时间戳
  184. datetime_format: 格式字符串 默认=%Y-%m-%d %H:%M:%S
  185. return: 2019-05-15 15:37:41 -> str
  186. """
  187. return time.strftime(datetime_format, time.localtime(seconds))
  188. def getAnyDateSecondTime(day, hour=0, min=0, sec=0):
  189. """
  190. description: 获取距离现在时间的任意时间的秒数
  191. day: 天数 1代表当前时间+1天 -1代表当前时间-1天
  192. hour: 小时 2代表当前时间+2h -2代表当前时间-2h 默认=0
  193. min: 分钟 30代表当前时间+30min -30代表当前时间-30m 默认=0
  194. sec: 秒 120代表当前时间+120s -120代表当前时间-120s 默认=0
  195. return: 1557902182 -> str
  196. """
  197. anyDay = datetime.datetime.now() + datetime.timedelta(days=day, hours=hour, minutes=min, seconds=sec)
  198. return str(round(time.mktime(anyDay.timetuple())))
  199. def getTodayStartTime():
  200. """
  201. description: 获取当天0点的时间戳
  202. return: 1557676800 -> str
  203. """
  204. return int(time.mktime(datetime.date.today().timetuple()))
  205. def getTodayEndTime():
  206. """
  207. description: 获取今天23点59分59秒的时间戳
  208. return: 1601049599 -> str
  209. """
  210. yesterday = datetime.date.today() + datetime.timedelta(days=1)
  211. return int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d'))) - 1
  212. def getYesterdayStartTime():
  213. """
  214. description: 获取昨天0点的时间戳
  215. return: 1557676800 -> int
  216. """
  217. yesterday = datetime.date.today() - datetime.timedelta(days=1)
  218. return int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d')))
  219. def getYesterdayEndTime():
  220. """
  221. description: 获取昨天23点59分59秒的时间戳
  222. return: 1601049599 -> int
  223. """
  224. return int(time.mktime(time.strptime(str(datetime.date.today()), '%Y-%m-%d'))) - 1
  225. def getTomorrowStartTime():
  226. """
  227. description: 获取明天0点的时间戳
  228. return: 1557676800 -> int
  229. """
  230. tomorrow = datetime.date.today() + datetime.timedelta(days=1)
  231. return int(time.mktime(time.strptime(str(tomorrow), '%Y-%m-%d')))
  232. def getTomorrowEndTime():
  233. """
  234. description: 获取明天23点59分59秒的时间戳
  235. return: 1601049599 -> str
  236. """
  237. yesterday = datetime.date.today() + datetime.timedelta(days=2)
  238. return int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d'))) - 1
  239. def getPreviousHourAndCurrentHourSecondTime(seconds=getCurrentSecondTime()):
  240. """
  241. description: 接受时间戳并返回上一小时整点时间和当前小时整点时间
  242. seconds: 默认当前时间 可传second
  243. return: 1602313200,1602316800 -> (previous_hour_second_time,current_hour_second_time)
  244. tips: seconds 不传参则取当前时间
  245. """
  246. previous_hour_second_time = int(seconds // 3600 * 3600 - 3600)
  247. current_hour_second_time = int(seconds // 3600 * 3600)
  248. return previous_hour_second_time, current_hour_second_time
  249. def getPrevious2HourAndCurrentHourSecondTime(seconds=getCurrentSecondTime()):
  250. """
  251. description: 接受时间戳并返回上2小时整点时间和当前小时整点时间
  252. seconds: 默认当前时间 可传second
  253. return: 1602313200,1602316800 -> (previous_hour_second_time,current_hour_second_time)
  254. tips: seconds 不传参则取当前时间
  255. """
  256. previous_hour_second_time = int(seconds // 3600 * 3600 - 7200)
  257. current_hour_second_time = int(seconds // 3600 * 3600)
  258. return previous_hour_second_time, current_hour_second_time
  259. def getCurrentWeekTime():
  260. """
  261. description: 获取本周周一0点
  262. return: 1557676800 -> str
  263. tips: 可替换成: timestamps = time.mktime(time.strptime(time.strftime("%Y-%m-%d", time.localtime(times)), "%Y-%m-%d"))
  264. """
  265. week = int(time.strftime("%w", time.localtime()))
  266. times = round(time.time()) - (week - 1) * 86400
  267. timestamps = time.mktime(datetime.date.fromtimestamp(times).timetuple())
  268. return str(round(timestamps))
  269. def checkInterval(start_time, end_time, need_compare_time):
  270. """
  271. description: 判断 need_compare_time 是否在 start_time 和 end_time区间里
  272. return: true -> bool
  273. """
  274. return need_compare_time >= start_time and need_compare_time < end_time
  275. def getSelfDateStr(times=time.time(),date_format='%Y%m%d'):
  276. """
  277. ## 20201028添加,阳光接口,日期参数请求格式20201028,一日一拉api数据
  278. description: 获取指定时间戳
  279. time: 秒 默认当前时间
  280. return: 返回指定时间戳的前一日日期 。 比如 :接收20190512号的时间戳,返回 20190513 -> str
  281. tips: 一天86400秒
  282. """
  283. timestamps = str(time.strftime(date_format,time.localtime(times)))
  284. return timestamps
  285. def getTodayStart(myday,flag=0):
  286. if flag:
  287. return datetime.datetime.strptime(myday+" 00:00:00",'%Y-%m-%d %H:%M:%S')
  288. else:
  289. return myday+" 00:00:00"
  290. def getTodayEnd(myday,flag=0):
  291. if flag:
  292. return datetime.datetime.strptime(myday+" 23:59:59",'%Y-%m-%d %H:%M:%S')
  293. else:
  294. return myday+" 23:59:59"
  295. def get_n_day(n=0, is_timestamp=0, is_datetime=0):
  296. """默认返回字符串 2020-01-01
  297. """
  298. str = (datetime.datetime.now() + datetime.timedelta(days=n)).strftime("%Y-%m-%d")
  299. date1 = datetime.datetime.strptime(str, "%Y-%m-%d")
  300. stamp = int(time.mktime(time.strptime(str, "%Y-%m-%d")))
  301. if is_timestamp:
  302. return stamp
  303. elif is_datetime:
  304. return date1
  305. else:
  306. return str
  307. def stamp_to_str(stamp):
  308. a = time.localtime(stamp)
  309. return time.strftime("%Y-%m-%d %H:%M:%S", a)
  310. def getTodayOrYestoday():
  311. """
  312. 如果当天零点 则返回昨天
  313. 否则返回今天
  314. :return:
  315. """
  316. if datetime.datetime.today().hour == 0:
  317. return get_n_day(-1,is_timestamp=1)
  318. else:
  319. return get_n_day(0,is_timestamp=1)
  320. if __name__ == '__main__':
  321. # print(test())
  322. # print(datetime.datetime.today().hour)
  323. print(getTodayOrYestoday())
  324. # print(getTodayEnd('2020-01-01'))
  325. # print(stamp_to_str(get_n_day(is_timestamp=1)))