datetime.timedelta对象代表两个时间之间的的时间差,两个date或datetime对象相减时可以返回一个timedelta对象。
构造函数:
class
datetime.
timedelta
(
[
days
[
,
seconds
[
,
microseconds
[
,
milliseconds
[
,
minutes
[
,
hours
[
,
weeks
]
]
]
]
]
]
]
)
所有参数可选,且默认都是0,参数的值可以是整数,浮点数,正数或负数。
内部只存储
days,seconds,microseconds,其他参数的值会自动按如下规则抓转换:
- 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
如果任意参数是float,且小数点后含有microseconds部分,那么microseconds的值为所有参数的微秒部分的总和(四舍五入)如:
>>> datetime.timedelta(hours=1.232,seconds=20).microseconds
200000
>>> datetime.timedelta(hours=1.232,seconds=20.3).microseconds
500000
支持的操作有:
1 = t2 + t3 | 两个timedelta对象相加,同时满足 t1-t2 == t3 and t1-t3 == t2 为True |
t1 = t2 - t3 | 两个timedelta对象相减, 同时满足 t1 == t2 - t3 and t2 == t1 + t3 为True |
t1 = t2 * i or t1 = i * t2 | timedelta对象分别乘以i 同时满足 t1 // i == t2 为True, 且 i != 0 |
t1 = t2 // i | 向下取整,余数部分被丢弃 |
+t1 | 返回和t1相同值的timedelta对象 |
-t1 | 取反操作,等价于timedelta(-t1.days, -t1.seconds, -t1.microseconds)和 t1* -1 |
abs(t) | 绝对值,等价于: +t 当 t.days >= 0, -t 当 t.days < 0 |
str(t) | 返回字符串,格式为: [D day[s], ][H]H:MM:SS[.UUUUUU] |
repr(t) | 返回字符串,格式为: datetime.timedelta(D[, S[, U]]) |
此外,timedelta和可以和date,datetime对象进行加减操作,如:
>>> datetime.datetime.now()
datetime.datetime(2013, 5, 23, 10, 49, 27, 182057)
>>> datetime.datetime.now()+datetime.timedelta(2)
datetime.datetime(2013, 5, 25, 10, 49, 29, 385559)
Python2.7新增了方法:
timedelta.
total_seconds
(
)
用于计算秒数。等价于:(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
实例1:
'''时间d距离now()的长度,比如:1分钟前,1小时前,1月前,1年前'''
# -*- encoding=UTF-8 -*-
import datetime
def timebefore(d):
chunks = (
(60 * 60 * 24 * 365, u'年'),
(60 * 60 * 24 * 30, u'月'),
(60 * 60 * 24 * 7, u'周'),
(60 * 60 * 24, u'天'),
(60 * 60, u'小时'),
(60, u'分钟'),
)
#如果不是datetime类型转换后与datetime比较
if not isinstance(d, datetime.datetime):
d = datetime.datetime(d.year,d.month,d.day)
now = datetime.datetime.now()
delta = now - d
#忽略毫秒
before = delta.days * 24 * 60 * 60 + delta.seconds #python2.7直接调用 delta.total_seconds()
#刚刚过去的1分钟
if before <= 60:
return u'刚刚'
for seconds,unit in chunks:
count = before // seconds
if count != 0:
break
return unicode(count)+unit+u"前"
实例2:
‘’‘当前的时间上加一天或一年减一天等操作’‘’
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from datetime import datetime,timedelta
now = datetime.now()
yestoday = now - timedelta(days=1)
tommorow = now + timedelta(days=1)
next_year = now + timedelta(days = 365)
参考:http://docs.python.org/2/library/datetime.html