Skip to content

Instantly share code, notes, and snippets.

@otienog1
Forked from andreif/python convert timezone.py
Created August 27, 2018 06:48
Show Gist options
  • Save otienog1/1ce52e42d590f79ff064268fc63d7f8c to your computer and use it in GitHub Desktop.
Save otienog1/1ce52e42d590f79ff064268fc63d7f8c to your computer and use it in GitHub Desktop.
from datetime import datetime, timezone, timedelta
def convert_timezone(dtm, z='utc'):
t_utc = (dtm - (dtm.utcoffset() or timedelta()))
t_utc = t_utc.replace(tzinfo=timezone.utc)
z = z.lower().replace('utc', '').replace(' ', '').replace(':', '')
if not z:
return t_utc
if len(z) == 3:
z += '00'
t_z = datetime.strptime(z, '%z')
t = (t_utc + t_z.utcoffset()).replace(tzinfo=t_z.tzinfo)
return t
s = 'Fri, 18 Sep 2015 20:32:59 +0200'
f = '%a, %d %b %Y %H:%M:%S %z'
t = datetime.strptime(s, f)
for (s, zz) in sorted({
'2015-09-18T18:32:59+00:00': ',UTC,+0000,utc,UtC',
'2015-09-18T19:32:59+01:00': 'UTC+0100,+0100,+01',
'2015-09-18T16:32:59-02:00': 'UTC-0200,-0200,-02',
}.items()):
for z in sorted(set(zz.split(','))):
x = convert_timezone(t, z).isoformat()
assert s == x, (z, s, x)
print(repr(z))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment