在Python中确定“天数”,当timedelta.days小于某个值时

2024-06-16 11:45:29 发布

您现在位置:Python中文网/ 问答频道 /正文

如果这是密件,请提前道歉。我正在努力寻找自从我上次发布推特以来的日子。我遇到的问题是日期不同时,例如今天和昨天,但是没有足够的时间来度过一个完整的“一天”

# "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”也没用,因为如果我今天发了微博,我希望结果是0。

有没有比使用timedelta获得差异更好的方法?


解决方案由Matti Lyra提供

答案是在datetimes上调用.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

Tags: ofthetodatetimeisdtdays
2条回答

就把约会时间的“约会”部分处理一下怎么样?

在以下代码中输出“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

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

相关问题 更多 >