如果这很密集,请提前道歉。我正在尝试查找自上次发布推文以来的天数。我遇到的问题是日期不同,例如今天和昨天,但还没有足够的时间成为完整的“一天”。
# "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
最佳答案
如何只处理日期时间的“日期”部分?
以下代码输出“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
关于python - 当 timedelta.days 小于 1 时,在 python 中确定 "days",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14635486/