To compare time from the file, you should convert it to UTC time (POSIX timestamp) or an aware datetime object (local time + utc offset).
start_time, end_time = get_times('hour', -3, -1.2)
if start_time <= utc_time < end_time:
# utc_time is in between
You should not use start_time <= naive_local_time < end_time
. Convert input time to UTC or create an aware datetime objects instead.
If local times in your input file are consecutive then you could use that fact to disambiguate the timestamps if necessary, see Parsing of Ordered Timestamps in Local Time (to UTC) While Observing Daylight Saving Time.
More explanation and solutions that use time.mktime()
, pytz
, aware datetime objects are in: Find if 24 hrs have passed between datetimes - Python.
Why you should not use datetime.now()
datetime.now()
returns local time as a naive datetime object may be ambiguous e.g., during a DST transition:
>>> from datetime import datetime
>>> import pytz
>>> tz = pytz.timezone('America/New_York')
>>> tz.localize(datetime(2015,11,1,1,30), is_dst=None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/pytz/tzinfo.py", line 349, in localize
raise AmbiguousTimeError(dt)
pytz.exceptions.AmbiguousTimeError: 2015-11-01 01:30:00
>>> tz.localize(datetime(2015,11,1,1,30), is_dst=True).astimezone(pytz.utc)
datetime.datetime(2015, 11, 1, 5, 30, tzinfo=<UTC>)
>>> tz.localize(datetime(2015,11,1,1,30), is_dst=False).astimezone(pytz.utc)
datetime.datetime(2015, 11, 1, 6, 30, tzinfo=<UTC>)
Note: if you remove UTC offset then the same local time may correspond to different UTC time. datetime.utcnow()
is unambiguous (except perhaps during a leap second such as 2015-06-30T23:59:60Z
).
How to implement get_times('hour', -3.0, -1.2)
Use UTC time or aware datetime objects:
#!/usr/bin/env python
from datetime import datetime, timedelta
def get_times(unit, relative_start, relative_end):
relative_start, relative_end = [timedelta(**{unit+'s': v})
for v in [relative_start, relative_end]]
now = datetime.utcnow() # or datetime.now(timezone.utc).astimezone()
return now + relative_start, now + relative_end