这几乎与我停止使用 time 并开始使用datetime
.
from datetime import tzinfo, timedelta, datetime
now = datetime.utcnow()
later = now - timedelta(seconds=40)
>>> now
datetime.datetime(2013, 10, 7, 15, 9, 5, 903000)
>>> print now
2013-10-07 15:09:05.903000
>>> print later
2013-10-07 15:08:25.903000
所以现在你可以减去差额。
now = datetime.utcnow()
later = now + timedelta(weeks=78, minutes=85, seconds=128)
diff = later - now
不幸的是,日期时间不会将天转换为月/年。我认为这是因为它必须计算闰年以及两个日期之间的月份。
>>> print diff
546 days, 1:27:08
额外信息:
如果您开始进入其他时区,它会变得有点复杂,因为您需要提供一个时区对象。这是一个简单的版本:
################################################################################
#Class definition for EST timezone since python doesn't have one
class EST(tzinfo):
def utcoffset(self, dt):
return timedelta(-5)
def tzname(self, dt):
return "EST"
def dst(self, dt):
return timedelta(0)
################################################################################
#Class definition for CST timezone since python doesn't have one
class CST(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=-6)
def tzname(self, dt):
return "CST"
def dst(self, dt):
return timedelta(0)
nowcst = datetime.now(tz=CST())
nowest = now.replace(tzinfo(EST())
使用时区确实应该考虑夏令时。
*示例代码可以在 python 文档中找到 - http://docs.python.org/2/library/datetime.html#tzinfo-objects