在python中,当timedelta.days小于1时如何确定“天数”
抱歉如果这段话有点复杂。我想找出自从我上次发推特以来过去了多少天。问题在于,当日期不同时,比如今天和昨天,但还没有过去足够的小时数来算作完整的“天”时,我就遇到了麻烦。
# "created_at" is part of the Twitter API, returned as UTC time. The
# timedelta here is to account for the fact I am on the west coast, USA
lastTweetAt = result.created_at + timedelta(hours=-8)
# get local time
rightNow = datetime.now()
# subtract the two datetimes (which gives me a timedelta)
dt = rightNow - lastTweetAt
# print the number of days difference
print dt.days
问题是,如果我昨天晚上5点发了一条推特,而今天早上8点运行这个脚本,那么只过去了15个小时,这算作0天。但显然,如果我昨天发过推特,我想说已经过去了1天。而简单地加上“+1”并不能解决问题,因为如果我今天发过推特,我希望结果是0。
有没有比使用时间差(timedelta)来计算差值更好的方法呢?
解决方案 由Matti Lyra提供
答案是对日期时间调用.date(),这样它们就会被转换为更简单的日期对象(没有时间戳)。正确的代码看起来是:
# "created_at" is part of the Twitter API, returned as UTC time.
# the -8 timedelta is to account for me being on the west coast, USA
lastTweetAt = result.created_at + timedelta(hours=-8)
# get UTC time for right now
rightNow = datetime.now()
# truncate the datetimes to date objects (which have dates, but no timestamp)
# and subtract them (which gives me a timedelta)
dt = rightNow.date() - lastTweetAt.date()
# print the number of days difference
print dt.days
2 个回答
13
你想怎么处理你日期时间中的“日期”部分呢?
下面这段代码中,输出“0”之后的部分:
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now() - datetime.timedelta(hours=20)
>>> (a-b).days
0
>>> b.date() - a.date()
datetime.timedelta(-1)
>>> (b.date() - a.date()).days
-1
14
你可以使用 datetime.date()
来比较两个日期(注意:这里指的是没有时间的日期),这样做会把 datetime
的精度调整为天,而不是小时。
...
# subtract the two datetimes (which gives me a timedelta)
dt = rightNow.date() - lastTweetAt.date()
...
文档总是你的好朋友
http://docs.python.org/2/library/datetime#datetime.datetime.date