判断日期时间之间是否已过去 24 小时
- 2024-12-09 08:30:00
- admin 原创
- 137
问题描述:
我有以下方法:
# last_updated is a datetime() object, representing the last time this program ran
def time_diff(last_updated):
day_period = last_updated.replace(day=last_updated.day + 1,
hour=1,
minute=0,
second=0,
microsecond=0)
delta_time = day_period - last_updated
hours = delta_time.seconds // 3600
# make sure a period of 24hrs have passed before shuffling
if hours >= 24:
print "hello"
else:
print "do nothing"
我想要了解是否已经过去了 24 小时last_updated
,如何用 Python 来实现呢?
解决方案 1:
如果last_updated
是一个简单的 datetime 对象,表示 UTC 时间:
from datetime import datetime, timedelta
if (datetime.utcnow() - last_updated) > timedelta(hours=24):
# more than 24 hours passed
如果last_updated
是当地时间(简单(不了解时区)日期时间对象):
import time
DAY = 86400
now = time.time()
then = time.mktime(last_updated.timetuple())
if (now - then) > DAY:
# more than 24 hours passed
如果last_updated
是一个不明确的时间,例如夏令时 (DST) 结束转换期间的时间(许多时区每年一次),那么有一半的机会mktime()
返回错误的结果(例如,偏差一小时)。
time.mktime()
如果 Ctime
库未在给定平台上使用历史时区数据库,并且本地时区的 UTC 偏移量与last_updated
现在不同,则也可能会失败。它可能适用于去年所有时区的三分之一以上。Linux、OS X、Windows 的最新版本都有 tz 数据库(我不知道旧 Windows 版本是否适用于这些过去的日期)。
注意:这样写可能很诱人datetime.now() - last_updated
(类似于 UTC 的情况),但是如果 UTC 偏移量在last_updated
时间上不同(在许多时区都有可能),那么它肯定会在所有平台上失败。mktime()
基于 tz 的解决方案至少在某些平台上可以利用 tz 数据库,因此它可以处理因任何原因导致的 UTC 偏移量的变化。
为了便于移植,你可以安装 tz 数据库。它由pytz
Python 中的模块提供。tzlocal
可以返回pytz
与当地时区相对应的时区:
from datetime import datetime, timedelta
from tzlocal import get_localzone # $ pip install tzlocal
tz = get_localzone() # local timezone
then = tz.normalize(tz.localize(last_updated)) # make it timezone-aware
now = datetime.now(tz) # timezone-aware current time in the local timezone
if (now - then) > timedelta(hours=24):
# more than 24 hours passed
即使 UTC 偏移量在过去不同,它也能正常工作。但它不能(以及time.mktime()
)修复模糊时间(默认tz.localize()
选择时间)。被调用来调整不存在的时间,例如,那些与 DST 转换开始相对应的时间(它不应该影响结果)。is_dst=False
`tz.normalize()`
上述代码假设last_updated
是一个简单的日期时间对象(没有关联的时区信息)。如果last_updated
是感知日期时间对象,则很容易将其转换为 UTC:
from datetime import datetime, timedelta
then_in_utc = last_updated.replace(tzinfo=None) - last_updated.utcoffset()
if (datetime.utcnow() - then_in_utc) > timedelta(hours=24):
# more than 24 hours passed
一般说明:您现在应该明白为什么人们建议使用 UTC 时间并仅使用本地时间进行显示。
解决方案 2:
只是为了澄清一些事情,因为我认为我们并不是所有人都使用了time
Python 库。当您使用时datetime
,这在 Django 中是一种非常常见的做法,如果您像这样进行比较:
if (now - then) > DAY:
它将遭遇巨大失败。这是因为你无法datetime.timedelta
与之相比int
。
解决方案是将对象转换为秒。
例如:
from datetime import datetime
then = datetime_object
now = datetime.now()
if (now - then).total_seconds() > NUMBER_OF_SECONDS:
# do something
希望我能够帮助到遇到此问题的人。
谢谢