• 主页

  • 投资

  • IT

    🔥
  • 设计

  • 销售

关闭

返回栏目

关闭

返回python栏目

73 - 自带库 - datetime - 时间

作者:

贺及楼

成为作者

更新日期:2024-10-27 18:04:29

datetime - 时间

datetime 库

Python 的 time 库用于处理时间相关的功能。它提供了获取当前时间、测量时间间隔、延迟执行代码以及转换时间格式等方法。time 库允许程序以秒或更精确的单位进行时间测量,支持不同操作系统的时间函数。它在日志记录、性能测试、动画制作、延迟任务调度等需要时间控制的场景中非常有用。

https://blog.csdn.net/gty931008/article/details/80254806

引入

  1. import datetime

datetime.date 类 日期

解释 例子 class类
datetime.date 年月日 datetime.date(2022, 4, 23)
datetime.time 时分秒微秒 datetime.time(21, 5, 35, 8888) class datetime.time(hour, [minute[, second, [microsecond[, tzinfo]]]])
datetime.datetime 年月日时分秒微秒 datetime.datetime(2017, 2, 4, 20, 44, 56, 572615) class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
datetime.timedelta 时长 datetime.timedelta(days=3) class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, hours=0, weeks=0)
datetime.tzinfo 时区相关信息
datetime.timezone 表示与UTC的固定偏移量
解释 代码 结果 规则
最小日期 min = datetime.date.min datetime.date(1, 1, 1)
最大日期 max = datetime.date.max datetime.date(9999, 12, 31)
今天 today = datetime.date.today() datetime.date(2022, 4, 23)
今天年份 year = datetime.date.today().year 2022
今天月份 month = datetime.date.today().month 4
今天日 day = datetime.date.today().day 23
daynumber = datetime.date.today().toordinal() 738268 返回日期是是自 0001-01-01 开始的第多少天
星期几-1 weekday = datetime.date.today().weekday() 5 返回日期是星期几,[0, 6],0表示星期一
星期几 isoweekday = datetime.date.today().isoweekday() 6 返回日期是星期几,[1, 7], 1表示星期一
第几周 week_number_u = datetime.datetime.now().strftime("%U") "50" 以周日为每周第一天
第几周 week_number_w = datetime.datetime.now().strftime("%W") "50" 以周一为每周第一天
day = datetime.date.today().isocalendar() (2022, 16, 6) 返回一个元组,格式为:(year, weekday, isoweekday)
day = datetime.date.today().isoformat() 2022-04-23 返回”YYYY-MM-DD”格式的日期字符串
day = datetime.date.today().strftime("%Y/%m/%d") 2022/04/23 指定形式
day = datetime.date.today().strftime("%Y-%m-%d") 2022-04-23 指定形式
day = datetime.date.today().strftime("%Y%m%d") 20220423 指定形式
day = datetime.date.today().timetuple() 下方代码 返回日期对应的time.struct_time对象

time.struct_time(tm_year=2022, tm_mon=4, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=113, tm_isdst=-1)

datetime.time 类 时间

解释 代码 结果 规则
最大时间 max = datetime.time.max datetime.time(23, 59, 59, 999999)
最小时间 time.min datetime.time(0, 0)
time.resolution datetime.timedelta(0, 0, 1)
小时 hour = datetime.time(23, 5, 35, 8888).hour 23
分钟 minute = datetime.time(23, 5, 35, 8888).minute 5
second = datetime.time(23, 5, 35, 8888).second 35
微秒 microsecond = datetime.time(23, 5, 35, 8888).microsecond 8888
tzinfo = datetime.time(23, 5, 35, 8888).tzinfo None 返回传递给time构造方法的tzinfo对象,如果该参数未给出,则返回None
replace = datetime.time(23, 5, 35, 8888).replace(21) datetime.time(21, 5, 35, 8888) t.replace(hour[, minute[, second[, microsecond[, tzinfo]]]]) 生成并返回一个新的时间对象,原时间对象不变
固定字符串 isoformat = datetime.time(23, 5, 35, 8888).isoformat() "23:05:35.008888" 返回一个"HH:MM:SS.%f"格式的时间字符串
自定义字符串 strftime = datetime.time(23, 5, 35, 8888).strftime("%H%M%S") 230535 返回指定格式的时间字符串
自定义字符串 strftime = datetime.time(23, 5, 35, 8888).strftime("%H%M%S.%f") 230535.008888 返回指定格式的时间字符串

datetime.datetime 类 日期 + 时间

解释 代码 结果 规则
现在 datetime.date.today() datetime.date(2022, 7, 16)
现在 datetime.datetime.now() datetime.datetime(2017, 2, 4, 20, 44, 56, 572615)
现在(时区) datetime.datetime.now(timezone.utc) datetime.datetime(2017, 2, 4, 12, 45, 22, 881694, tzinfo=datetime.timezone.utc)
现在(无时区) datetime.datetime.utcnow() datetime.datetime(2017, 2, 4, 12, 45, 52, 812508)
根据时间戳创建 datetime.datetime.fromtimestamp(time.time()) datetime.datetime(2017, 2, 4, 20, 46, 41, 97578)
根据时间戳创建 datetime.datetime.utcfromtimestamp(time.time()) datetime.datetime(2017, 2, 4, 12, 46, 56, 989413)
date和time对象整合成一个datetime对象 datetime.date.combine(date(2017, 2, 4), t) datetime.datetime(2017, 2, 4, 20, 5, 40, 8888)
字符串转换为datetime对象 datetime.datetime.strptime("2017/02/04 20:49", "%Y/%m/%d %H:%M") datetime.datetime(2017, 2, 4, 20, 49)
现在 dt = datetime.datetime.now() datetime.datetime(2017, 2, 4, 20, 57, 0, 621378)
今年 year = datetime.date.now().year 2017
这个月 month = datetime.date.now().month 2
今天 day = datetime.date.now().day 4
这个小时 hour = datetime.datetime.now().hour 20
这分钟 minute = datetime.datetime.now().minute 57
这秒 second = datetime.datetime.now().second 0
这微妙 microsecond = datetime.datetime.now().microsecond 621378
tzinfo = datetime.date.now().tzinfo
时间戳 timestamp = datetime.datetime.now().timestamp() 1486213020.621378
年月日 date = datetime.datetime.now().date() datetime.date(2017, 2, 4)
时分秒微妙 time = datetime.datetime.now().time() datetime.time(20, 57, 0, 621378)
timetz = datetime.now().timetz() datetime.time(20, 57, 0, 621378)
更改 replace = datetime.datetime.now().replace() datetime.datetime(2017, 2, 4, 20, 57, 0, 621378)
更改 replace = datetime.datetime.now().replace(2016) datetime.datetime(2016, 2, 4, 20, 57, 0, 621378)
时间元组 timetuple = datetime.datetime.now().timetuple() time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=20, tm_min=57, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1)
时间元组 utctimetuple = datetime.datetime.now().utctimetuple() time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=20, tm_min=57, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=0)
toordinal = datetime.datetime.now().toordinal() 736364
weekday = datetime.datetime.now().weekday() 5
isocalendar = datetime.datetime.now().isocalendar() (2017, 5, 6)
isoformat = datetime.datetime.now().isoformat() "2017-02-04T20:57:00.621378"
isoformat = datetime.datetime.now().isoformat(sep=”/“) "2017-02-04/20:57:00.621378"
isoformat = datetime.datetime.now().isoformat(sep=” “) "2017-02-04 20:57:00.621378"
ctime = datetime.datetime.now().ctime() "Sat Feb 4 20:57:00 2017"
自定义格式化 strftime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") "2017-02-04 20:57:00.621378"

datetime.timedelta 类 时间差(日、周、小时、分钟、秒)

  1. def __new__(cls, days=0, seconds=0, microseconds=0,milliseconds=0, minutes=0, hours=0, weeks=0):
解释 代码 结果 规则
一年包含的总秒数 datetime.timedelta(365).total_seconds() 31536000.0
3天 dt = datetime.timedelta(3) datetime.timedelta(days=3)
3天后 dt = datetime.datetime.now() + datetime.timedelta(3) datetime.datetime(2017, 2, 8, 9, 39, 40, 102821)
3天前 dt = datetime.datetime.now() + datetime.timedelta(-3) datetime.datetime(2017, 2, 2, 9, 39, 40, 102821)
3小时后 dt = datetime.datetime.now() + datetime.timedelta(hours=3) datetime.datetime(2017, 2, 5, 12, 39, 40, 102821)
3小时前 dt = datetime.datetime.now() + datetime.timedelta(hours=-3) datetime.datetime(2017, 2, 5, 6, 39, 40, 102821)
3小时30秒后 dt = datetime.datetime.now() + datetime.timedelta(hours=3, seconds=30) datetime.datetime(2017, 2, 5, 12, 40, 10, 102821)

获得小时数、秒数

  1. from datetime import datetime, timedelta
  2. ## 假设有两个时间点
  3. time1 = datetime(2023, 3, 15, 8) # 2023年3月15日 8时
  4. time2 = datetime(2023, 3, 16, 10) # 2023年3月16日 10时
  5. ## 计算两个时间点之间的timedelta
  6. delta = time2 - time1
  7. print(delta)
  8. ## 获取delta的小时数
  9. hours = delta.total_seconds() / 3600 # 26.0
  10. second = delta.total_seconds() # 93600.0 秒
  11. print(f"两个时间之间的差异为:{hours} 小时")
  12. print(f"两个时间之间的差异为:{second} 秒")

时间差获得小时数、秒数

relativedelta()时间差(年月日周小时、分钟、秒)

  1. def __init__(self, dt1=None, dt2=None,
  2. years=0, months=0, days=0, leapdays=0, weeks=0,hours=0, minutes=0, seconds=0, microseconds=0,year=None, month=None, day=None, weekday=None,yearday=None, nlyearday=None,hour=None, minute=None, second=None, microsecond=None):
  3. ## 使用
  4. from dateutil.relativedelta import relativedelta
  5. now = datetime.datetime.now() # 现在是2023年11月
  6. latest_time = now+relativedelta(months=-15) # 减15个月,跨年了
  7. print(latest_time)
  8. ## datetime.datetime(2022, 8, 21, 9, 28, 17, 458687)

replace()直接替换修改日期

  1. def replace(self, year=None, month=None, day=None, hour=None,minute=None, second=None, microsecond=None, tzinfo=True,*, fold=None):
  2. now = datetime.datetime.now() # 现在是2023年11月
  3. latest_time = now.replace(month=10,day=1)
  4. ## datetime.datetime(2023, 10, 1, 11, 7, 56, 806271)

replace直接替换修改日期

对比时间大小

  1. import datetime
  2. timenow = datetime.timedelta(hours=8, minutes=29)
  3. timenow = datetime.timedelta(hours=8, minutes=31)
  4. time830 = datetime.timedelta(hours=8, minutes=30)
  5. if timenow < time830 :
  6. print("0:00-8:30") # 29
  7. else:
  8. print("8:30-23:59") # 31

对比时间大小

n天前的列表

  1. def get_nday_list(n):
  2. before_n_days = []
  3. for i in range(0, n)[::-1]:
  4. day = str(datetime.date.today() - datetime.timedelta(days=i))
  5. day2 = day.replace("-","")
  6. before_n_days.append(day2)
  7. return before_n_days

n天前列表

一天一天的列表

  1. import datetime
  2. def daybyday(t1, t2):
  3. tt1 = datetime.datetime.strptime(t1, "%Y-%m-%d %H:%M:%S")
  4. tt2 = datetime.datetime.strptime(t2, "%Y-%m-%d %H:%M:%S")
  5. cha = tt2 - tt1
  6. chadays = cha.days
  7. if chadays == 0:
  8. # 第一种情况,例如chadays等于0days,在一天内
  9. if tt1.day == tt2.day:
  10. print("在一天内")
  11. return [[t1,t2]]
  12. # 第二种情况,例如chadays等于0days,在两天内
  13. if tt1.day != tt2.day:
  14. print("在两天内")
  15. month = addzero(str(tt1.month))
  16. day = addzero(str(tt1.day))
  17. t1_last = str(tt1.year) + "-" + month + "-" + day + " 23:59:59"
  18. month = addzero(str(tt2.month))
  19. day = addzero(str(tt2.day))
  20. t2_start = str(tt2.year) + "-" + month + "-" + day + " 00:00:00"
  21. return [[t1, t1_last], [t2_start, t2]]
  22. if chadays > 0:
  23. print("在多天内")
  24. # 第三种情况,例如chadays大于0days
  25. datelist = []
  26. # 第一天
  27. first_day = []
  28. month = addzero(str(tt1.month))
  29. day = addzero(str(tt1.day))
  30. first_day.append(t1)
  31. first_day.append(str(tt1.year) + "-" + month + "-" + day + " 23:59:59")
  32. datelist.append(first_day)
  33. # 中间天
  34. for i in range(cha.days):
  35. datel = []
  36. if i == 0:
  37. continue
  38. tt1_add = tt1 + datetime.timedelta(i)
  39. month = addzero(str(tt1_add.month))
  40. day = addzero(str(tt1_add.day))
  41. datel.append(str(tt1_add.year) + "-" + month + "-" + day + " 00:00:00")
  42. datel.append(str(tt1_add.year) + "-" + month + "-" + day + " 23:59:59")
  43. datelist.append(datel)
  44. # 最后一天
  45. last_day = []
  46. month = addzero(str(tt2.month))
  47. day = addzero(str(tt2.day))
  48. last_day.append(str(tt2.year) + "-" + month + "-" + day + " 00:00:00")
  49. last_day.append(t2)
  50. datelist.append(last_day)
  51. return datelist
  52. def addzero(data):
  53. if len(data) == 1:
  54. data = "0"+data
  55. return data
  56. def run():
  57. # t1 = "2022-07-01 03:00:00"
  58. # t2 = "2022-07-01 04:00:00"
  59. # t1 = "2022-07-01 23:00:00"
  60. # t2 = "2022-07-02 01:00:00"
  61. t1 = "2022-06-25 03:00:00"
  62. t2 = "2022-07-09 15:00:00"
  63. datelist = daybyday(t1, t2)
  64. print(datelist)
  65. if __name__ == "__main__":
  66. run()
  67. # [["2022-07-01 03:00:00", "2022-07-01 04:00:00"]]
  68. # [["2022-07-01 23:00:00", "2022-07-01 23:59:59"],
  69. # ["2022-07-02 00:00:00", "2022-07-02 01:00:00"]]
  70. # [["2022-06-25 03:00:00", "2022-06-25 23:59:59"],
  71. # ["2022-06-26 00:00:00", "2022-06-26 23:59:59"],
  72. # ["2022-06-27 00:00:00", "2022-06-27 23:59:59"],
  73. # ["2022-06-28 00:00:00", "2022-06-28 23:59:59"],
  74. # ["2022-06-29 00:00:00", "2022-06-29 23:59:59"],
  75. # ["2022-06-30 00:00:00", "2022-06-30 23:59:59"],
  76. # ["2022-07-01 00:00:00", "2022-07-01 23:59:59"],
  77. # ["2022-07-02 00:00:00", "2022-07-02 23:59:59"],
  78. # ["2022-07-03 00:00:00", "2022-07-03 23:59:59"],
  79. # ["2022-07-04 00:00:00", "2022-07-04 23:59:59"],
  80. # ["2022-07-05 00:00:00", "2022-07-05 23:59:59"],
  81. # ["2022-07-06 00:00:00", "2022-07-06 23:59:59"],
  82. # ["2022-07-07 00:00:00", "2022-07-07 23:59:59"],
  83. # ["2022-07-08 00:00:00", "2022-07-08 23:59:59"],
  84. # ["2022-07-09 00:00:00", "2022-07-09 15:00:00"]]