Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

python - Find if 24 hrs have passed between datetimes

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...