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