Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 759
cybertextron Avatar asked Oct 11 '14 10:10

cybertextron


People also ask

How do you check if a day has passed Python?

example. from datetime import datetime NUMBER_OF_SECONDS = 86400 # seconds in 24 hours first = datetime(2017, 10, 10) second = datetime(2017, 10, 12) if (first - second). total_seconds() > NUMBER_OF_SECONDS: print("its been over a day!")

How do I find the difference between two Datetimes in Python?

timedelta() method. To find the difference between two dates in Python, one can use the timedelta class which is present in the datetime library. The timedelta class stores the difference between two datetime objects.

How do I get time difference between hours in Python?

total_seconds() methods. Multiply the total seconds by 1000 to get the time difference in milliseconds. Divide the seconds by 60 to get the difference in minutes. Divide the seconds by 3600 to get the final result in hours.


1 Answers

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

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(hours=24):
    # 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(hours=24):
    # 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.

like image 90
jfs Avatar answered Oct 19 '22 14:10

jfs