# "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 :(得分:8)
您可以使用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
答案 1 :(得分:6)
如何处理日期时间的“日期”部分?
以下代码中输出“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