查找日期时间之间是否经过了 24 小时
问题描述
我有以下方法:
# 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"
我想知道自 last_updated
以来是否已经过了 24 小时,我该如何在 Python 中做到这一点?
I want to find out if 24 hrs have passed since last_updated
, how can I do that in Python?
解决方案
如果 last_updated
是一个朴素的 datetime 对象,表示 UTC 时间:
If last_updated
is a naive datetime object representing the time in UTC:
from datetime import datetime, timedelta
if (datetime.utcnow() - last_updated) > timedelta(hours=24):
# more than 24 hours passed
如果 last_updated
是本地时间(naive (timezone-unaware) datetime 对象):
If last_updated
is the local time (naive (timezone-unaware) datetime object):
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()
返回错误的结果(例如,关闭一个小时).
If last_updated
is an ambiguous time e.g., the time during an end-of-DST transition (once a year in many timezones) then there is a fifty-fifty chance that mktime()
returns a wrong result (e.g., off by an hour).
time.mktime()
如果 C time
库不使用给定平台上的历史时区数据库并且也可能失败last_updated
时间与现在相比,本地时区的 UTC 偏移量不同.它可能适用于去年超过三分之一的时区.Linux、OS X、Windows 的最新版本都有 tz 数据库(我不知道旧的 Windows 版本是否适用于这些过去的日期).
time.mktime()
may also fail if C time
library doesn't use a historical timezone database on a given platform and the UTC offset for the local timezone was different at last_updated
time compared to now. It may apply to more than a third of all timezones in the last year. Linux, OS X, the recent versions of Windows have the tz database (I don't know whether old Windows versions would work for such past dates).
注意:写 datetime.now() - last_updated
可能很诱人(类似于 UTC 情况),但如果 last_updated
时间(在许多时区都有可能).基于 mktime()
的解决方案至少可以在某些平台上利用 tz 数据库,因此无论出于何种原因,它都可以处理 UTC 偏移量的变化.
Beware: it might be tempting to write datetime.now() - last_updated
(similar to the UTC case) but it is guaranteed to fail on all platforms if the UTC offset was different at last_updated
time (it is possible in many timezones). mktime()
-based solution can utilize the tz database at least on some platforms and therefore it can handle the changes in the UTC offset for whatever reason there.
为了便携性,您可以安装 tz 数据库.它由 Python 中的 pytz
模块提供.tzlocal
可以返回本地时区对应的pytz
时区:
For portability, you could install the tz database. It is provided by pytz
module in Python. tzlocal
can return pytz
timezone corresponding to the local timezone:
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()
选择 is_dst=False
时间默认情况下).调用 tz.normalize()
来调整不存在的时间,例如,对应于 DST 转换开始的时间(它不应该影响结果).
It works even if the UTC offset was different in the past. But it can't (as well as time.mktime()
) fix ambiguous times (tz.localize()
picks is_dst=False
time by default). tz.normalize()
is called to adjust non-existing times e.g., those that correspond to a start-of-DST transition (it should not affect the result).
上面的代码假定 last_updated
是一个简单的日期时间对象(没有关联的时区信息).如果 last_updated
是一个可感知的日期时间对象,那么很容易将其转换为 UTC:
The above code assumes that last_updated
is a naive datetime object (no associated timezone info). If last_updated
is an aware datetime object then it is easy to convert it to 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 时间并仅使用本地时间进行显示.
General note: you should understand now why people recommend to work with UTC time and to use local time only for display.
相关文章