I am working with SQLAlchemy, and I’m not yet sure which database I’ll use under it, so I want to remain as DB-agnostic as possible. How can I store a timezone-aware datetime object in the DB without tying myself to a specific database? Right now, I’m making sure that times are UTC before I store them in the DB, and converting to localized at display-time, but that feels inelegant and brittle. Is there a DB-agnostic way to get a timezone-aware datetime out of SQLAlchemy instead of getting naive datatime objects out of the DB?
Share
There is a
timezoneparameter toDateTimecolumn time, so there is no problem with storing timezone-awaredatetimeobjects. However I found convenient to convert storeddatetimeto UTC automatically with simple type decorator:Note, that is behaves nicely when you use naive
datetimeby accident (meaning it will raise a ValueError).