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

标签 python date datetime 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

问题是,如果我昨天下午 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/

相关文章:

python 3 - 读取压缩存档中的文件将 'b' 字符放在每行的开头

python - 从 python 调用时,udisks FilesystemUnmount 似乎不存在

Java 日期和标准格式

Php 获取一个日期还剩多少天和几小时

java - DatePicker 显示从 0 开始的月份值

python - 有没有比 for 循环更快的方法来忽略日期并在日期时间系列中获取特定时间?

python - 使用线程将 stdout 重定向到 Tkinter 文本小部件的问题

java - 在 Java 中将日期转换为 C# 刻度

Python - 在特定时区设置日期时间(没有 UTC 转换)

python - 使用pdb调试Python时如何打印所有变量值,而不指定每个变量?