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

cyb*_*ron 14 python timezone datetime

我有以下方法:

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

我想知道从那以后24小时过去了last_updated,我怎么能这样做last_updated呢?

jfs*_*jfs 18

如果last_updated是一个天真的日期时间对象,表示UTC时间:

from datetime import datetime, timedelta

if (datetime.utcnow() - last_updated) > timedelta(1): 
    # more than 24 hours passed
Run Code Online (Sandbox Code Playgroud)

如果last_updated是本地时间(天真(timezone-unaware)日期时间对象):

import time

DAY = 86400
now = time.time()
then = time.mktime(last_updated.timetuple())
if (now - then) > DAY:
    # more than 24 hours passed
Run Code Online (Sandbox Code Playgroud)

如果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
Run Code Online (Sandbox Code Playgroud)

即使UTC偏移在过去不同,它也能工作.但它不能(以及time.mktime())修复模糊时间(默认tz.localize()选择is_dst=False时间).tz.normalize()被调用以调整不存在的时间,例如,对应于DST开始转换的那些时间(它不应该影响结果).

上面的代码假设这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(1):
    # more than 24 hours passed
Run Code Online (Sandbox Code Playgroud)

一般说明:您现在应该了解为什么人们建议使用UTC时间并仅使用当地时间进行显示.