28

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?

3 Answers 3

45

There is a timezone parameter to DateTime column time, so there is no problem with storing timezone-aware datetime objects. However I found convenient to convert stored datetime to UTC automatically with simple type decorator:

from sqlalchemy import types
from datetime import datetime, timezone

class UTCDateTime(types.TypeDecorator):

    impl = types.DateTime

    def process_bind_param(self, value, engine):
        if value is None:
            return
        if value.utcoffset() is None:
            raise ValueError(
                'Got naive datetime while timezone-aware is expected'
            )
        return value.astimezone(timezone.utc)

    def process_result_value(self, value, engine):
        if value is not None:
            return value.replace(tzinfo=timezone.utc)

Note, that is behaves nicely when you use naive datetime by accident (meaning it will raise a ValueError).

9
  • 11
    @Jesse Dhillon: it's intentional to prevent accidental storage of naive datetime objects, while your recipe incorrectly inteprets any datetime with any timezone as being UTC. Aug 4, 2010 at 3:35
  • 6
    @Dennis, so using your type, one is expected to create and store only timezone-aware datetime objects? Now that I understand that, I like your solution more because it requires the user to be explicit about what they are saving. Aug 4, 2010 at 5:37
  • 4
    Would I be correct in thinking that the last bit, where it creates the datetime, is equivalent to value.replace(tzinfo=tzutc()) as seen here: mindlace.net/2012/11/13/… ? Or does one do something slightly different? I'm scared of getting something wrong here! Jan 18, 2013 at 11:49
  • 1
    @OrganicPanda Yes, it's possible to simplify it as you described. Both expressions evaluate to the same value. You can test it yourself by substituting value for any datetime object. Feb 25, 2016 at 12:16
  • 1
    The SQLAlchemy docs has a recipe: docs.sqlalchemy.org/en/14/core/…
    – codeape
    Dec 9, 2020 at 9:45
2

I am addressing the desire to have datetime-aware in my code by using UTC in all internal instances. The only issue I came up with was when reading the database. Despite writing datetime-aware to the database, when retrieving the format is naive. My fix was:

import pytz

dt = mydb.query.filter_by(name='test').first().last_update.replace(tzinfo=pytz.utc)
  • dt is the variable that will store the last_update retrieved in datetime format
  • mydb is the name of my db table
  • name is one of the columns in the table
  • last_update is a column that is stored in the format datetime

The trick is replace(tzinfo=pytz.utc)

1

The SQLAlchemy documentation has a recipe for this:

import datetime

class TZDateTime(TypeDecorator):
    impl = DateTime

    def process_bind_param(self, value, dialect):
        if value is not None:
            if not value.tzinfo:
                raise TypeError("tzinfo is required")
            value = value.astimezone(datetime.timezone.utc).replace(
                tzinfo=None
            )
        return value

    def process_result_value(self, value, dialect):
        if value is not None:
            value = value.replace(tzinfo=datetime.timezone.utc)
        return value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.