Python datetime 模块之timedelta

timedalte 是datetime中的一个对象,该对象表示两个时间的差值

构造函数: datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
其中参数都是可选,默认值为0

下面应该是常识,几乎每个人都知道:


1 millisecond = 1000 microseconds
1 minute = 60 seconds
1 hour = 3600 seconds

1 week = 7 days


在构造函数中,参数值的范围如下:


0 <= microseconds < 1000000
0 <= seconds < 3600*24 (the number of seconds in one day)
-999999999 <= days <= 999999999



timedalte 有三个只读属性:


timedelta.min:负数最大时间差,相当于  timedelta(-999999999)。
timedelta.max:正数最大时间差,相当于  timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)。

timedelta.resolution:两个时间的最小差值 相当于   timedelta(microseconds=1)。


三个只读属性实例:

from datetime import date,timedelta
print(timedelta.max);#999999999 days, 23:59:59.999999
print(timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999));#999999999 days, 23:59:59.999999

print(timedelta.min);#-999999999 days, 0:00:00
print(timedelta(-999999999));#-999999999 days, 0:00:00

print(timedelta.resolution);#0:00:00.000001
print(timedelta(microseconds=1));#0:00:00.000001

timedelta.total_seconds()方法:返回该时间差 以秒为单位的值


综上的实例:

from datetime import datetime,date,timedelta
now = datetime.now();
nextDay = now + timedelta(days = 1);#增加一天后的时间
nextSecond = now + timedelta(seconds = 1);#增加一秒后的时间
span  = now - nextDay;#获取时间差对象
print(now);
print(nextDay);
print(nextSecond);
print(span.total_seconds());#获取时间差 以秒为单位

以上为了学习整理了一下,如有错误,麻烦指正。谢谢

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值