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:If
last_updated
is the local time (naive (timezone-unaware) datetime object):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 thatmktime()
returns a wrong result (e.g., off by an hour).time.mktime()
may also fail if Ctime
library doesn't use a historical timezone database on a given platform and the UTC offset for the local timezone was different atlast_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 atlast_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 returnpytz
timezone corresponding to the local timezone: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()
picksis_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). Iflast_updated
is an aware datetime object then it is easy to convert it to UTC:General note: you should understand now why people recommend to work with UTC time and to use local time only for display.
Just to clear our some things, because I don't think all of us make use of the
time
Python lib. When you usedatetime
, which is especially in Django a very common practice, if you do the comparison like this:it will hugely fail. This is because you can't compare
datetime.timedelta
toint
.The solution to this is to convert your objects to seconds.
For example:
Hope I helped out whoever faced issues on that.
Cheers