找到24小时之间的数据时间之间 - Python [英] Find if 24 hrs have passed between datetimes - Python

查看:254
本文介绍了找到24小时之间的数据时间之间 - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

 #last_updated是一个datetime()对象,表示该程序上次运行
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
#确保在洗牌前已经过了24小时
如果小时> = 24:
printhello
else:
打印do nothing

我想知道从 last_updated 以来是否已经过了24小时,我该如何在 Python

解决方案

如果 last_updated 是表示UTC时间的天真的datetime对象: p>

  from datetime import datetime,timedelta 

if(datetime .utcnow() - last_updated)> timedelta(1):
#超过24小时通过

如果 last_updated 是本地时间(naive(timezone-unaware)datetime对象):

 导入时间

DAY = 86400
now = time.time()
then = time.mktime(last_updated.timetuple())
if(now - then)> DAY:
#超过24小时通过

如果 last_updated 是一个模糊的时间,例如,在DST结束转换期间(在许多时区每年一次)的时间,那么有一个五十五次机会, mktime() code>返回错误的结果(例如,关闭一小时)。



time.mktime()也可能会失败,如果C 时间库不使用给定平台上的历史时区数据库,本地时区的UTC偏移量不同在 last_updated 时间比现在。它可能适用于去年的三分之一以上的时区。 Linux,OS X,Windows的最新版本有tz数据库(我不知道旧的Windows版本是否适用于过去的日期)。



小心:它可能很有可能写入 datetime.now() - last_updated (类似于UTC的情况),但如果UTC偏移量在 last_updated 时间(可能在许多时区)。 mktime()解决方案可以至少在某些平台上使用tz数据库,因此无论何种原因,它都可以处理UTC偏移量的变化。



为了便于携带,您可以安装tz数据库。它由Python中的 pytz 模块提供。 tzlocal 可以返回对应于本地时区的 pytz 时区:

  from datetime import datetime,timedelta 
from tzlocal import get_localzone#$ pip install tzlocal

tz = get_localzone()#local timezone
然后= tz.normalize(tz.localize(last_updated))#使其timezone-aware
now = datetime.now(tz)#当地时区的当前时间区域
if(now - then )> timedelta(1):
#超过24小时通过

即使UTC偏移量在过去是不同的。但是它不能(以及 time.mktime())修复不明确的时间( tz.localize()默认选择 is_dst = False 时间)。调用 tz.normalize()来调整不存在的时间,例如对应于DST开始转换的时间(不应影响结果)。 p>

上述代码假定 last_updated 是一个天真的datetime对象(没有关联的时区信息)。如果 last_updated 是一个感知的datetime对象,那么很容易将其转换为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):
#超过24小时通过

一般说明:你应该明白现在为什么人们建议使用UTC时间,并使用本地时间来显示。


I have the following method:

# 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"

I want to find out if 24 hrs have passed since last_updated, how can I do that in Python?

解决方案

If last_updated is a naive datetime object representing the time in UTC:

from datetime import datetime, timedelta

if (datetime.utcnow() - last_updated) > timedelta(1): 
    # more than 24 hours passed

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

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() 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).

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.

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(1):
    # more than 24 hours passed

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).

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(1):
    # more than 24 hours passed

General note: you should understand now why people recommend to work with UTC time and to use local time only for display.

这篇关于找到24小时之间的数据时间之间 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆