12 03 Time Zones and Daylight Saving - HannaAA17/Data-Scientist-With-Python-datacamp GitHub Wiki
Daylight Saving Time: the time during the summer when clocks are one hour ahead of standard time
UTC offsets
Set timezones manually
- US Eastern Standard time zone:
ET = timezone(timedelta(hours=-5))
- Set timezone-aware datetime:
dt = datetime(2017, 12, 30, 15, 9, 3, tzinfo=ET)
# Import datetime, timedelta, timezone
from datetime import datetime, timedelta, timezone
# Create a timezone for Pacific Standard Time, or UTC-8
pst = timezone(timedelta(hours=-8))
# October 1, 2017 at 15:26:26, UTC-8
dt = datetime(2017, 10, 1, 15, 26, 26, tzinfo=pst)
# Print results
print(dt.isoformat())
Adjusting timezone vs. changing tzinfo
dt.replace(tzinfo=timezone.utc)
: change the timedt.astimezone(timezone.utc)
: change the timezone to match UTC but still the same time
Timezone database
- tz database
from dateutil import tz
- format:
Continent/City
et = tz.gettz('America/New_York')
Starting daylight saving time
# Import datetime, timedelta, tz, timezone
from datetime import datetime, timedelta, timezone
from dateutil import tz
# Start on March 12, 2017, midnight, then add 6 hours
start = datetime(2017, 3, 12, tzinfo = tz.gettz('America/New_York'))
end = start + timedelta(hours = 6)
print(start.isoformat() + " to " + end.isoformat()) # 2017-03-12T00:00:00-05:00 to 2017-03-12T06:00:00-04:00
Added 6 hours, and got 6 AM, despite the fact that the clocks springing forward means only 5 hours would have actually elapsed!
# How many hours have elapsed?
print((end - start).total_seconds()/(60*60)) #6.0
# What if we move to UTC?
print((end.astimezone(tz.UTC) - start.astimezone(tz.UTC))\
.total_seconds()/(60*60)) #5.0
When we compare times in local time zones, everything gets converted into clock time. Remember if you want to get absolute time differences, always move to UTC!
Ending daylight saving time
- Ambiguous datetimes would occur since there are two '1am' on the day ending daylight saving time.
tz.datetime_ambiguous(datetime)
: True if it is ambiguous
tz.enfold(datetime)
: the datetime refers to the one after the daylight saving time change- But Python does not handle
tz.enfold()
when doing arithmetic, we must put our datetime objects into UTC, where ambiguities have been resolved.
- But Python does not handle
eastern = tz.gettz('US/Eastern')
# 2017-11-05 01:00:00
first_1am = datetime(2017, 11, 5, 1, 0, 0,tzinfo = eastern)
# 2017-11-05 01:00:00 again
second_1am = datetime(2017, 11, 5, 1, 0, 0, tzinfo = eastern)
second_1am = tz.enfold(second_1am)
(first_1am - second_1am).total_seconds() # 0.0
first_1am = first_1am.astimezone(tz.UTC)
second_1am = second_1am.astimezone(tz.UTC)
(first_1am - second_1am).total_seconds() # 3600.0