Skip to content

Instantly share code, notes, and snippets.

@avoiney
Last active November 1, 2021 13:30
Show Gist options
  • Save avoiney/fdcd0b0d91436526d2f3 to your computer and use it in GitHub Desktop.
Save avoiney/fdcd0b0d91436526d2f3 to your computer and use it in GitHub Desktop.
""" Tool function to convert Generalized Time string
to Python datetime object
"""
import datetime
import pytz
def gt_to_dt(gt):
""" Convert GeneralizedTime string to python datetime object
>>> gt_to_dt("20150131143554.230")
datetime.datetime(2015, 1, 31, 14, 35, 54, 230)
>>> gt_to_dt("20150131143554.230Z")
datetime.datetime(2015, 1, 31, 14, 35, 54, 230, tzinfo=<UTC>)
>>> gt_to_dt("20150131143554.230+0300")
datetime.datetime(2015, 1, 31, 11, 35, 54, 230, tzinfo=<UTC>)
"""
# check UTC and offset from local time
utc = False
if "Z" in gt.upper():
utc = True
gt = gt[:-1]
if gt[-5] in ['+', '-']:
# offsets are given from local time to UTC, so substract the offset to get UTC time
hour_offset, min_offset = -int(gt[-5] + gt[-4:-2]), -int(gt[-5] + gt[-2:])
utc = True
gt = gt[:-5]
else:
hour_offset, min_offset = 0, 0
# microseconds are optionnals
if "." in gt:
microsecond = int(gt[gt.index('.') + 1:])
gt = gt[:gt.index('.')]
else:
microsecond = 0
# seconds and minutes are optionnals too
if len(gt) == 14:
year, month, day, hours, minutes, sec = int(gt[:4]), int(gt[4:6]), int(gt[6:8]), int(gt[8:10]), int(gt[10:12]), int(gt[12:])
hours += hour_offset
minutes += min_offset
elif len(gt) == 12:
year, month, day, hours, minutes, sec = int(gt[:4]), int(gt[4:6]), int(gt[6:8]), int(gt[8:10]), int(gt[10:]), 0
hours += hour_offset
minutes += min_offset
elif len(gt) == 10:
year, month, day, hours, minutes, sec = int(gt[:4]), int(gt[4:6]), int(gt[6:8]), int(gt[8:]), 0, 0
hours += hour_offset
minutes += min_offset
else:
# can't be a generalized time
raise ValueError('This is not a generalized time string')
# construct aware or naive datetime
if utc:
dt = datetime.datetime(year, month, day, hours, minutes, sec, microsecond, tzinfo=pytz.UTC)
else:
dt = datetime.datetime(year, month, day, hours, minutes, sec, microsecond)
# done !
return dt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment