date_util.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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 getLastMonthDay():
  56. """
  57. 获取上月第一天和最后一天
  58. @returen str"""
  59. today = datetime.date.today()
  60. last_day_of_last_month = datetime.date(today.year, today.month, 1) - datetime.timedelta(1)
  61. first_day_of_last_month = datetime.date(last_day_of_last_month.year, last_day_of_last_month.month, 1)
  62. return first_day_of_last_month, last_day_of_last_month
  63. def getCurrentMilliSecondTime():
  64. """
  65. description: 获取当前时间-毫秒级
  66. return: 1557730376981 -> str
  67. """
  68. timestamps = str(round(time.time() * 1000))
  69. return timestamps
  70. def getCurrentSecondTime():
  71. """
  72. description: 获取当前时间-秒级
  73. return: 1557730377 -> int
  74. """
  75. timestamps = int(time.time())
  76. return timestamps
  77. def getCurrentTimeTuple(times=time.time()):
  78. """
  79. description: 接受秒级时间戳并返回时间元组(与mktime(tuple)相反)
  80. times: 默认当前时间 可传second
  81. 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
  82. tips: time.localtime() 不传参则取当前时间
  83. """
  84. timestamps = time.localtime(times)
  85. return timestamps
  86. def getTimeByTuple(tupleTime=time.localtime()):
  87. """
  88. description: 接受时间元组并返回秒级时间戳(与localtime(sec)相反)
  89. tupleTime: 默认当前时间的元组 可通过time.localtime() or datetime.datetime.now().timetuple()获取
  90. return: 1557733061 -> str
  91. """
  92. timestamps = str(round(time.mktime(tupleTime)))
  93. return timestamps
  94. def getCurrentFormatTimeStr(times=time.time()):
  95. """
  96. description: 将指定时间元组格式化为字符串
  97. times: 默认当前时间 可传second
  98. return: 2019-05-13 15:00:47 -> str
  99. tips: %y 两位数的年份表示(00-99) %Y 四位数的年份表示(000-9999) %m 月份(01-12) %d 月内中的一天(0-31)
  100. %H 24小时制小时数(0-23) %I 12小时制小时数(01-12) %M 分钟数(00=59) %S 秒(00-59) %w 星期(0-6)
  101. """
  102. timestamps = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(times))
  103. return timestamps
  104. def getCurrentTimeTupleByFormatStr(time_str=str(datetime.datetime.now()).split(".")[0],
  105. format_type="%Y-%m-%d %H:%M:%S"):
  106. """
  107. description: 接受格式化字符串返回时间元组
  108. time_str: 格式化字符串 如:2019-05-13 15:00:47 默认当前时间
  109. format_type: 格式化规则 如:%Y-%m-%d %H:%M:%S 默认%Y-%m-%d %H:%M:%S
  110. 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
  111. """
  112. return time.strptime(time_str, format_type)
  113. def getCurrentTimeStr():
  114. """
  115. description: 获取当前时间的可读形式字符串
  116. return: Mon May 13 11:27:42 2019 -> str
  117. """
  118. return time.ctime()
  119. def getCurrentTimeStrByTuple(tupleTime=time.localtime()):
  120. """
  121. description: 获取指定时间的可读形式字符串
  122. tupleTime: 时间元组 可通过time.localtime() or datetime.datetime.now().timetuple()获取 默认当前时间的元组
  123. return: Mon May 13 11:27:42 2019 -> str
  124. """
  125. return time.asctime(tupleTime)
  126. def sleepTime():
  127. """
  128. description: 推迟调用线程的运行
  129. """
  130. for i in range(4):
  131. print(i)
  132. time.sleep(3)
  133. # ======================
  134. # ====== datetime ======
  135. # ======================
  136. def getNowDateTime():
  137. """
  138. description: 获取当前日期&时间
  139. return: 2019-05-13 14:41:15 -> str
  140. """
  141. timestamps = str(datetime.datetime.now()).split(".")[0]
  142. return timestamps
  143. def getNowTime():
  144. """
  145. description: 获取当前时间
  146. return: 14:41:15 -> str
  147. """
  148. timestamps = str(datetime.datetime.now().time()).split(".")[0]
  149. return timestamps
  150. def getTodayDate():
  151. """
  152. description: 获取当前日期
  153. return: 2019-05-13 -> str
  154. tipe: datetime.datetime.now().date()有相同效果
  155. """
  156. timestamps = str(datetime.date.today())
  157. return timestamps
  158. def getTimeDate(times=time.time()):
  159. """
  160. description: 获取指定时间戳的日期
  161. time: 秒 默认当前时间
  162. return: 2019-05-13 -> str
  163. tips: 一天86400秒
  164. """
  165. timestamps = str(datetime.date.fromtimestamp(round(times)))
  166. return timestamps
  167. def getAnyDateTime(day, hour=0, min=0, sec=0):
  168. """
  169. description: 获取距离现在时间的任意时间的日期&时间
  170. day: 天数 1代表当前时间+1天 -1代表当前时间-1天
  171. hour: 小时 2代表当前时间+2h -2代表当前时间-2h 默认=0
  172. min: 分钟 30代表当前时间+30min -30代表当前时间-30m 默认=0
  173. sec: 秒 120代表当前时间+120s -120代表当前时间-120s 默认=0
  174. return: 2019-05-15 15:37:41 -> str
  175. """
  176. return str(datetime.datetime.now() + datetime.timedelta(days=day, hours=hour, minutes=min, seconds=sec)).split(".")[
  177. 0]
  178. def getSecondsToDatetime(seconds=getCurrentSecondTime(), datetime_format="%Y-%m-%d %H:%M:%S"):
  179. """
  180. description: 秒/时间戳转日期字符串
  181. seconds: 时间戳 默认为当前时间戳
  182. datetime_format: 格式字符串 默认=%Y-%m-%d %H:%M:%S
  183. return: 2019-05-15 15:37:41 -> str
  184. """
  185. return time.strftime(datetime_format, time.localtime(seconds))
  186. def getAnyDateSecondTime(day, hour=0, min=0, sec=0):
  187. """
  188. description: 获取距离现在时间的任意时间的秒数
  189. day: 天数 1代表当前时间+1天 -1代表当前时间-1天
  190. hour: 小时 2代表当前时间+2h -2代表当前时间-2h 默认=0
  191. min: 分钟 30代表当前时间+30min -30代表当前时间-30m 默认=0
  192. sec: 秒 120代表当前时间+120s -120代表当前时间-120s 默认=0
  193. return: 1557902182 -> str
  194. """
  195. anyDay = datetime.datetime.now() + datetime.timedelta(days=day, hours=hour, minutes=min, seconds=sec)
  196. return str(round(time.mktime(anyDay.timetuple())))
  197. def getTodayStartTime():
  198. """
  199. description: 获取当天0点的时间戳
  200. return: 1557676800 -> str
  201. """
  202. return int(time.mktime(datetime.date.today().timetuple()))
  203. def getTodayEndTime():
  204. """
  205. description: 获取今天23点59分59秒的时间戳
  206. return: 1601049599 -> str
  207. """
  208. yesterday = datetime.date.today() + datetime.timedelta(days=1)
  209. return int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d'))) - 1
  210. def getYesterdayStartTime():
  211. """
  212. description: 获取昨天0点的时间戳
  213. return: 1557676800 -> int
  214. """
  215. yesterday = datetime.date.today() - datetime.timedelta(days=1)
  216. return int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d')))
  217. def getYesterdayEndTime():
  218. """
  219. description: 获取昨天23点59分59秒的时间戳
  220. return: 1601049599 -> int
  221. """
  222. return int(time.mktime(time.strptime(str(datetime.date.today()), '%Y-%m-%d'))) - 1
  223. def getTomorrowStartTime():
  224. """
  225. description: 获取明天0点的时间戳
  226. return: 1557676800 -> int
  227. """
  228. tomorrow = datetime.date.today() + datetime.timedelta(days=1)
  229. return int(time.mktime(time.strptime(str(tomorrow), '%Y-%m-%d')))
  230. def getTomorrowEndTime():
  231. """
  232. description: 获取明天23点59分59秒的时间戳
  233. return: 1601049599 -> str
  234. """
  235. yesterday = datetime.date.today() + datetime.timedelta(days=2)
  236. return int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d'))) - 1
  237. def getPreviousHourAndCurrentHourSecondTime(seconds=getCurrentSecondTime()):
  238. """
  239. description: 接受时间戳并返回上一小时整点时间和当前小时整点时间
  240. seconds: 默认当前时间 可传second
  241. return: 1602313200,1602316800 -> (previous_hour_second_time,current_hour_second_time)
  242. tips: seconds 不传参则取当前时间
  243. """
  244. previous_hour_second_time = int(seconds // 3600 * 3600 - 3600)
  245. current_hour_second_time = int(seconds // 3600 * 3600)
  246. return previous_hour_second_time, current_hour_second_time
  247. def getPrevious2HourAndCurrentHourSecondTime(seconds=getCurrentSecondTime()):
  248. """
  249. description: 接受时间戳并返回上2小时整点时间和当前小时整点时间
  250. seconds: 默认当前时间 可传second
  251. return: 1602313200,1602316800 -> (previous_hour_second_time,current_hour_second_time)
  252. tips: seconds 不传参则取当前时间
  253. """
  254. previous_hour_second_time = int(seconds // 3600 * 3600 - 7200)
  255. current_hour_second_time = int(seconds // 3600 * 3600)
  256. return previous_hour_second_time, current_hour_second_time
  257. def getCurrentWeekTime():
  258. """
  259. description: 获取本周周一0点
  260. return: 1557676800 -> str
  261. tips: 可替换成: timestamps = time.mktime(time.strptime(time.strftime("%Y-%m-%d", time.localtime(times)), "%Y-%m-%d"))
  262. """
  263. week = int(time.strftime("%w", time.localtime()))
  264. times = round(time.time()) - (week - 1) * 86400
  265. timestamps = time.mktime(datetime.date.fromtimestamp(times).timetuple())
  266. return str(round(timestamps))
  267. def checkInterval(start_time, end_time, need_compare_time):
  268. """
  269. description: 判断 need_compare_time 是否在 start_time 和 end_time区间里
  270. return: true -> bool
  271. """
  272. return need_compare_time >= start_time and need_compare_time < end_time
  273. def getSelfDateStr(times=time.time(),date_format='%Y%m%d'):
  274. """
  275. ## 20201028添加,阳光接口,日期参数请求格式20201028,一日一拉api数据
  276. description: 获取指定时间戳
  277. time: 秒 默认当前时间
  278. return: 返回指定时间戳的前一日日期 。 比如 :接收20190512号的时间戳,返回 20190513 -> str
  279. tips: 一天86400秒
  280. """
  281. timestamps = str(time.strftime(date_format,time.localtime(times)))
  282. return timestamps
  283. def getTodayStart(myday,flag=0):
  284. if flag:
  285. return datetime.datetime.strptime(myday+" 00:00:00",'%Y-%m-%d %H:%M:%S')
  286. else:
  287. return myday+" 00:00:00"
  288. def getTodayEnd(myday,flag=0):
  289. if flag:
  290. return datetime.datetime.strptime(myday+" 23:59:59",'%Y-%m-%d %H:%M:%S')
  291. else:
  292. return myday+" 23:59:59"
  293. def get_n_day(n=0, is_timestamp=0, is_datetime=0):
  294. """默认返回字符串 2020-01-01
  295. """
  296. str = (datetime.datetime.now() + datetime.timedelta(days=n)).strftime("%Y-%m-%d")
  297. date1 = datetime.datetime.strptime(str, "%Y-%m-%d")
  298. stamp = int(time.mktime(time.strptime(str, "%Y-%m-%d")))
  299. if is_timestamp:
  300. return stamp
  301. elif is_datetime:
  302. return date1
  303. else:
  304. return str
  305. def stamp_to_str(stamp):
  306. a = time.localtime(stamp)
  307. return time.strftime("%Y-%m-%d %H:%M:%S", a)
  308. if __name__ == '__main__':
  309. # print(test())
  310. # print(getTodayEnd('2020-01-01'))
  311. print(stamp_to_str(get_n_day(is_timestamp=1)))