Skip to content

Instantly share code, notes, and snippets.

@jbylund
Created July 15, 2020 21:08
Show Gist options
  • Save jbylund/13c50fc1a771597ddb0a7b969a13246b to your computer and use it in GitHub Desktop.
Save jbylund/13c50fc1a771597ddb0a7b969a13246b to your computer and use it in GitHub Desktop.
PARSEPATTERN = re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})T(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})\.000Z")
def _parse_timestamp_with_tzinfo(value, tzinfo):
"""Parse timestamp with pluggable tzinfo options."""
if isinstance(value, (str,)):
match = PARSEPATTERN.match(value)
if match is not None:
try:
return datetime.datetime(**{k: int(v) for k, v in match.groupdict().items()}).replace(tzinfo=tzinfo())
except ValueError:
pass
if isinstance(value, (int, float)):
# Possibly an epoch time.
return datetime.datetime.fromtimestamp(value, tzinfo())
else:
try:
return datetime.datetime.fromtimestamp(float(value), tzinfo())
except (TypeError, ValueError):
pass
try:
# In certain cases, a timestamp marked with GMT can be parsed into a
# different time zone, so here we provide a context which will
# enforce that GMT == UTC.
return dateutil.parser.parse(value, tzinfos={'GMT': tzutc()})
except (TypeError, ValueError) as e:
raise ValueError('Invalid timestamp "%s": %s' % (value, e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment