Skip to content

Instantly share code, notes, and snippets.

@DSamuylov
Last active October 20, 2018 22:10
Show Gist options
  • Save DSamuylov/2c7d299e438c9cb2467c3db6f4d17214 to your computer and use it in GitHub Desktop.
Save DSamuylov/2c7d299e438c9cb2467c3db6f4d17214 to your computer and use it in GitHub Desktop.
Example of how to convert: [localised timestamp] <-> [timestamp in UTC encoded in ISO string and UTC offset in seconds].
import datetime
import pytz
import dateutil.parser
from typing import Tuple
def encode(ts: datetime.datetime) -> Tuple[str, float]:
"""Return string encoding timestamp in UTC in ISO format and timezone offset in seconds."""
if ts.tzinfo is None:
raise Exception(f"Provide localised timestamp: tzinfo={ts.tzinfo}")
utc_ts = pytz.utc.normalize(ts)
utc_offset = ts.utcoffset()
return utc_ts.isoformat(), utc_offset.total_seconds()
def decode(utc_ts: str, utc_offset: float) -> datetime.datetime:
"""Construct timestamp from the string encoding timestamp in UTC in ISO format and timezone offset in seconds."""
ts = dateutil.parser.isoparse(utc_ts)
if ts.tzinfo != dateutil.tz.tzutc():
raise Exception(f"Provide timestamp in UTC. You provided: {ts.tzinfo}")
return ts.astimezone(dateutil.tz.tzoffset(name=None, offset=utc_offset))
if __name__ == "__main__":
t = datetime.datetime.now()
assert t.tzinfo is None
timezone = pytz.timezone("Europe/Zurich")
t_localised = timezone.localize(t)
utc_ts, utc_offset = encode(t_localised)
assert decode(utc_ts=utc_ts, utc_offset=utc_offset) == t_localised
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment