小编典典

Python-查找日期时间之间是否经过了24小时

python

我有以下方法:

# 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中做到这一点?


阅读 536

收藏
2020-02-11

共1个答案

小编典典

If last_updated是一个简单的datetime对象,表示UTC时间:

from datetime import datetime, timedelta

if (datetime.utcnow() - last_updated) > timedelta(1): 
    # 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()如果C time库没有在给定平台上使用历史时区数据库,并且本地时区的UTC偏移last_updated时间与现在相比有所不同,也可能会失败。它可能适用于过去一年中所有时区的三分之一以上。Linux,OS X和Windows的最新版本都具有tz数据库(我不知道旧的Windows版本是否可以在过去的日期使用)。

当心:可能很容易写datetime.now() - last_updated(类似于UTC的情况),但是如果UTC偏移last_updated时间不同(在许多时区都是可能的),则保证在所有平台上都失败。mktime()基于解决方案的解决方案至少可以在某些平台上使用tz数据库,因此无论存在什么原因,它都可以处理UTC偏移量的变化。

为了实现可移植性,你可以安装tz数据库。它由pytzPython中的模块提供。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(1):
    # more than 24 hours passed

即使UTC偏移量过去不同,它也可以工作。但是它不能(以及time.mktime())解决不明确的时间(默认情况下tz.localize()选择is_dst=False时间)。tz.normalize()调用来调整不存在的时间,例如,与DST转换开始相对应的时间(它不应影响结果)。

上面的代码假定这last_updated是一个简单的datetime对象(没有关联的时区信息)。如果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(1):
    # more than 24 hours passed

一般说明:你现在应该了解为什么人们建议使用UTC时间并且仅将本地时间用于显示。

2020-02-11