18

如果这很密集,请提前道歉。我试图找出自上次发布推文以来的日子。我遇到的问题是日期不同时,例如今天和昨天,但没有足够的时间过去成为一个完整的“一天”。

# "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
4

2 回答 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
于 2013-01-31T21:36:37.497 回答
12

您可以使用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

于 2013-01-31T21:35:42.677 回答