Save a timezone-aware datetime to a string, then restore it back to a datetime later

Viewed 57

I'm reading a postgres database and getting a datetime object. I'd like to save this in a text file, and then later re-read it and get an equivalent datetime object. In both cases I need to be timezone aware.

How do I do this in a way that will reliably work, even if the later re-reading is done in a different locale or timezone?

1 Answers
import datetime
import pytz

loc = datetime.datetime.now()  # local time without timezone
loc = pytz.timezone('CET').localize(loc)  # make timezone aware

with open("out.txt", "w") as w:
    w.write(loc.isoformat())  # write in iso 8601 format...

with open("out.txt", "r") as r:
    dt = datetime.datetime.fromisoformat(r.read())
    print(dt)
    print(dt == loc)
Related