date_util.py 12 KB

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