当timedelta.days小于1时,在python中确定"days"

psx*_*ndc 12 python datetime date timedelta

如果这是密集的,请提前抱歉.我试图找到自上次发布推文以来的日子.我遇到的问题是日期不同,例如今天和昨天,但没有足够的时间过去是一个完整的"日子".

# "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, 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
Run Code Online (Sandbox Code Playgroud)

Mat*_*yra 8

您可以datetime.date()用来比较两个日期(注意:NOT日期和时间),这会截断日期datetime的分辨率而不是小时数.

...
# subtract the two datetimes (which gives me a timedelta)
dt = rightNow.date() - lastTweetAt.date()
...
Run Code Online (Sandbox Code Playgroud)

文档永远是你的朋友

http://docs.python.org/2/library/datetime#datetime.datetime.date


Bor*_*jaX 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
Run Code Online (Sandbox Code Playgroud)