Need to use timezone-aware datetime values in the sqlalchemy ORM, but want to store the UTC values? Use tzaware_datetime.


tzaware_datetime uses sqlalchemy's composite columns feature to store a UTC datetime value as well as the offset, in seconds, of the given datetime. This allows sqlalchemy to sort dates by a common timezone, and retains the "local" time.


See for a complete example.

  1. from tzaware_datetime import TZAwareDateTime
  2. Add three tzaware_datetime-specific columns when setting up the Table object (or call helper.append_columns(newtable, columnname))
  3. Add the composite column mapping to the mapper (or call helper.get_mapper_definition(newtable, columnname) when preparing the mapper)
  4. Add values to the new column by adding a TZAwareDateTime() object, with the realdate parameter set.
  5. Retrieve values by reading yourtable.tzawaredate.realdate (for the timezone-specific date), or yourtable.tzawaredate.utcdt for the UTC date.


author: Andrew Ittner
© 2010
Last modified 2021-08-09