Last active
July 14, 2020 17:10
-
-
Save rambo/3972720 to your computer and use it in GitHub Desktop.
Testing/comparing pytz and dateutil for timezone handling in timezone with multiple historical UTC offsets and DST (run in interactive shell)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://pypi.python.org/pypi/pytz | |
import datetime, pytz | |
fmt = '%Y-%m-%d %H:%M:%S %Z%z' | |
hki = pytz.timezone('Europe/Helsinki') | |
hki | |
dt_n = datetime.datetime(2012, 10, 29, 10, 34, 0) | |
hki.utcoffset(dt_n) | |
td = datetime.timedelta(days=20) | |
dt2_n = dt - td | |
hki.utcoffset(dt2_n) | |
dt_a = dt_n.replace(tzinfo=hki) | |
dt_a | |
dt_a.strftime(fmt) | |
dt_a_norm = hki.normalize(dt_a) | |
dt_a_norm | |
dt_a_norm.strftime(fmt) | |
dt2_a = dt_a - td | |
dt2_a | |
dt2_a.strftime(fmt) | |
dt2_a_norm = hki.normalize(dt2_a) | |
dt2_a_norm | |
dt2_a_norm.strftime(fmt) | |
dt3_a = datetime.datetime(2012, 10, 29, 10, 34, 0, tzinfo=hki) | |
dt3_a | |
dt3_a.strftime(fmt) | |
# http://pypi.python.org/pypi/python-dateutil | |
import datetime | |
from dateutil import tz as timezone | |
fmt = '%Y-%m-%d %H:%M:%S %Z%z' | |
hki = timezone.gettz('Europe/Helsinki') | |
hki | |
dt_n = datetime.datetime(2012, 10, 29, 10, 34, 0) | |
hki.utcoffset(dt_n) | |
td = datetime.timedelta(days=20) | |
dt2_n = dt - td | |
hki.utcoffset(dt2_n) | |
dt_a = dt_n.replace(tzinfo=hki) | |
dt_a | |
dt_a.strftime(fmt) | |
dt2_a = dt_a - td | |
dt2_a | |
dt2_a.strftime(fmt) | |
dt3_a = datetime.datetime(2012, 10, 29, 10, 34, 0, tzinfo=hki) | |
dt3_a | |
dt3_a.strftime(fmt) | |
# This is actaully the wrong result, it should hae been compensated for summer time as pytz does (though I can envision scenarios where that would not be desirable...) | |
dt4_a = dt3_a - td | |
dt4_a | |
dt4_a.strftime(fmt) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime as datetime_mod | |
import pytz | |
def convertTime(timestamp): | |
hki = pytz.timezone('Europe/Helsinki') | |
utc = pytz.UTC | |
naive = datetime_mod.datetime(int(timestamp[:4]), int(timestamp[4:6]), int(timestamp[6:8]), int(timestamp[8:10]), int(timestamp[10:12]), 0, 0) | |
aware = hki.localize(naive) | |
utcstamp = aware.astimezone(utc) | |
print "naive=%s, aware=%s, utc=%s" % (repr(naive), repr(aware), repr(utcstamp)) | |
return utcstamp | |
print convertTime("201310150930") | |
print convertTime("201310310930") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment