如果这是密集的,请提前抱歉.我试图找到自上次发布推文以来的日子.我遇到的问题是日期不同,例如今天和昨天,但没有足够的时间过去是一个完整的"日子".
# "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
Run Code Online (Sandbox Code Playgroud)
问题是,如果我昨天下午5点发布推文并且今天上午8点正在运行脚本,那么仅过了15个小时,即0天.但显然我想说自从我上一条推文以来已经过了1天,如果是昨天的话.并且添加"+1"的补丁并没有帮助,因为如果我今天发推文,我希望结果为0.
有没有比使用timedelta更好的方法来获得差异?
解决方案 由Matti Lyra提供
答案是在日期时调用.date(),以便将它们转换为更粗糙的日期对象(没有时间戳).正确的代码如下:
# "created_at" is part of the Twitter API, …
Run Code Online (Sandbox Code Playgroud)