Python timedelta对象用于表示时间间隔,可以通过以下方式初始化:
指定天、小时、分钟、秒和毫秒:
from datetime import timedelta
timedelta(days=2, hours=6, minutes=30, seconds=15, milliseconds=500)
从总秒数指定:
timedelta(seconds=3600) # 1 hour
从日期差指定:
end_date = datetime(2023, 1, 15)
start_date = datetime(2023, 1, 10)
timedelta(end_date - start_date)
从时间字符串指定:
timedelta(days=1, hours=2, minutes=30, seconds=15).total_seconds()
常见属性和方法:
- total_seconds():总秒数
- days、seconds、microseconds等属性
- add(other):相加
- subtract(other):相减
举例:
one_day = timedelta(days=1)
print(one_day) # 1 day, 0:00:00
ten_minutes = timedelta(minutes=10)
print(one_day + ten_minutes) # 1 day, 0:10:00