time_util.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. # -*- coding: utf-8 -*-
  2. # @Author : relakkes@gmail.com
  3. # @Time : 2023/12/2 12:52
  4. # @Desc : 时间相关的工具函数
  5. import time
  6. from datetime import datetime, timedelta, timezone
  7. def get_current_timestamp() -> int:
  8. """
  9. 获取当前的时间戳(13 位):1701493264496
  10. :return:
  11. """
  12. return int(time.time() * 1000)
  13. def get_current_time() -> str:
  14. """
  15. 获取当前的时间:'2023-12-02 13:01:23'
  16. :return:
  17. """
  18. return time.strftime('%Y-%m-%d %X', time.localtime())
  19. def get_current_date() -> str:
  20. """
  21. 获取当前的日期:'2023-12-02'
  22. :return:
  23. """
  24. return time.strftime('%Y-%m-%d', time.localtime())
  25. def get_time_str_from_unix_time(unixtime):
  26. """
  27. unix 整数类型时间戳 ==> 字符串日期时间
  28. :param unixtime:
  29. :return:
  30. """
  31. if int(unixtime) > 1000000000000:
  32. unixtime = int(unixtime) / 1000
  33. return time.strftime('%Y-%m-%d %X', time.localtime(unixtime))
  34. def get_date_str_from_unix_time(unixtime):
  35. """
  36. unix 整数类型时间戳 ==> 字符串日期
  37. :param unixtime:
  38. :return:
  39. """
  40. if int(unixtime) > 1000000000000:
  41. unixtime = int(unixtime) / 1000
  42. return time.strftime('%Y-%m-%d', time.localtime(unixtime))
  43. def get_unix_time_from_time_str(time_str):
  44. """
  45. 字符串时间 ==> unix 整数类型时间戳,精确到秒
  46. :param time_str:
  47. :return:
  48. """
  49. try:
  50. format_str = "%Y-%m-%d %H:%M:%S"
  51. tm_object = time.strptime(str(time_str), format_str)
  52. return int(time.mktime(tm_object))
  53. except Exception as e:
  54. return 0
  55. pass
  56. def get_unix_timestamp():
  57. return int(time.time())
  58. def rfc2822_to_china_datetime(rfc2822_time):
  59. # 定义RFC 2822格式
  60. rfc2822_format = "%a %b %d %H:%M:%S %z %Y"
  61. # 将RFC 2822时间字符串转换为datetime对象
  62. dt_object = datetime.strptime(rfc2822_time, rfc2822_format)
  63. # 将datetime对象的时区转换为中国时区
  64. dt_object_china = dt_object.astimezone(timezone(timedelta(hours=8)))
  65. return dt_object_china
  66. def rfc2822_to_timestamp(rfc2822_time):
  67. # 定义RFC 2822格式
  68. rfc2822_format = "%a %b %d %H:%M:%S %z %Y"
  69. # 将RFC 2822时间字符串转换为datetime对象
  70. dt_object = datetime.strptime(rfc2822_time, rfc2822_format)
  71. # 将datetime对象转换为UTC时间
  72. dt_utc = dt_object.replace(tzinfo=timezone.utc)
  73. # 计算UTC时间对应的Unix时间戳
  74. timestamp = int(dt_utc.timestamp())
  75. return timestamp
  76. if __name__ == '__main__':
  77. # 示例用法
  78. _rfc2822_time = "Sat Dec 23 17:12:54 +0800 2023"
  79. print(rfc2822_to_china_datetime(_rfc2822_time))