
Python 的 time 库用于处理时间相关的功能。它提供了获取当前时间、测量时间间隔、延迟执行代码以及转换时间格式等方法。time 库允许程序以秒或更精确的单位进行时间测量,支持不同操作系统的时间函数。它在日志记录、性能测试、动画制作、延迟任务调度等需要时间控制的场景中非常有用。
https://blog.csdn.net/gty931008/article/details/80254806
import datetime
| 类 | 解释 | 例子 | 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)
| 解释 | 代码 | 结果 | 规则 |
|---|---|---|---|
| 最大时间 | 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.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" |
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) |
from datetime import datetime, timedelta## 假设有两个时间点time1 = datetime(2023, 3, 15, 8) # 2023年3月15日 8时time2 = datetime(2023, 3, 16, 10) # 2023年3月16日 10时## 计算两个时间点之间的timedeltadelta = time2 - time1print(delta)## 获取delta的小时数hours = delta.total_seconds() / 3600 # 26.0second = delta.total_seconds() # 93600.0 秒print(f"两个时间之间的差异为:{hours} 小时")print(f"两个时间之间的差异为:{second} 秒")

def __init__(self, dt1=None, dt2=None,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):## 使用from dateutil.relativedelta import relativedeltanow = datetime.datetime.now() # 现在是2023年11月latest_time = now+relativedelta(months=-15) # 减15个月,跨年了print(latest_time)## datetime.datetime(2022, 8, 21, 9, 28, 17, 458687)
def replace(self, year=None, month=None, day=None, hour=None,minute=None, second=None, microsecond=None, tzinfo=True,*, fold=None):now = datetime.datetime.now() # 现在是2023年11月latest_time = now.replace(month=10,day=1)## datetime.datetime(2023, 10, 1, 11, 7, 56, 806271)

import datetimetimenow = datetime.timedelta(hours=8, minutes=29)timenow = datetime.timedelta(hours=8, minutes=31)time830 = datetime.timedelta(hours=8, minutes=30)if timenow < time830 :print("0:00-8:30") # 29else:print("8:30-23:59") # 31

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

import datetimedef daybyday(t1, t2):tt1 = datetime.datetime.strptime(t1, "%Y-%m-%d %H:%M:%S")tt2 = datetime.datetime.strptime(t2, "%Y-%m-%d %H:%M:%S")cha = tt2 - tt1chadays = cha.daysif chadays == 0:# 第一种情况,例如chadays等于0days,在一天内if tt1.day == tt2.day:print("在一天内")return [[t1,t2]]# 第二种情况,例如chadays等于0days,在两天内if tt1.day != tt2.day:print("在两天内")month = addzero(str(tt1.month))day = addzero(str(tt1.day))t1_last = str(tt1.year) + "-" + month + "-" + day + " 23:59:59"month = addzero(str(tt2.month))day = addzero(str(tt2.day))t2_start = str(tt2.year) + "-" + month + "-" + day + " 00:00:00"return [[t1, t1_last], [t2_start, t2]]if chadays > 0:print("在多天内")# 第三种情况,例如chadays大于0daysdatelist = []# 第一天first_day = []month = addzero(str(tt1.month))day = addzero(str(tt1.day))first_day.append(t1)first_day.append(str(tt1.year) + "-" + month + "-" + day + " 23:59:59")datelist.append(first_day)# 中间天for i in range(cha.days):datel = []if i == 0:continuett1_add = tt1 + datetime.timedelta(i)month = addzero(str(tt1_add.month))day = addzero(str(tt1_add.day))datel.append(str(tt1_add.year) + "-" + month + "-" + day + " 00:00:00")datel.append(str(tt1_add.year) + "-" + month + "-" + day + " 23:59:59")datelist.append(datel)# 最后一天last_day = []month = addzero(str(tt2.month))day = addzero(str(tt2.day))last_day.append(str(tt2.year) + "-" + month + "-" + day + " 00:00:00")last_day.append(t2)datelist.append(last_day)return datelistdef addzero(data):if len(data) == 1:data = "0"+datareturn datadef run():# t1 = "2022-07-01 03:00:00"# t2 = "2022-07-01 04:00:00"# t1 = "2022-07-01 23:00:00"# t2 = "2022-07-02 01:00:00"t1 = "2022-06-25 03:00:00"t2 = "2022-07-09 15:00:00"datelist = daybyday(t1, t2)print(datelist)if __name__ == "__main__":run()# [["2022-07-01 03:00:00", "2022-07-01 04:00:00"]]# [["2022-07-01 23:00:00", "2022-07-01 23:59:59"],# ["2022-07-02 00:00:00", "2022-07-02 01:00:00"]]# [["2022-06-25 03:00:00", "2022-06-25 23:59:59"],# ["2022-06-26 00:00:00", "2022-06-26 23:59:59"],# ["2022-06-27 00:00:00", "2022-06-27 23:59:59"],# ["2022-06-28 00:00:00", "2022-06-28 23:59:59"],# ["2022-06-29 00:00:00", "2022-06-29 23:59:59"],# ["2022-06-30 00:00:00", "2022-06-30 23:59:59"],# ["2022-07-01 00:00:00", "2022-07-01 23:59:59"],# ["2022-07-02 00:00:00", "2022-07-02 23:59:59"],# ["2022-07-03 00:00:00", "2022-07-03 23:59:59"],# ["2022-07-04 00:00:00", "2022-07-04 23:59:59"],# ["2022-07-05 00:00:00", "2022-07-05 23:59:59"],# ["2022-07-06 00:00:00", "2022-07-06 23:59:59"],# ["2022-07-07 00:00:00", "2022-07-07 23:59:59"],# ["2022-07-08 00:00:00", "2022-07-08 23:59:59"],# ["2022-07-09 00:00:00", "2022-07-09 15:00:00"]]