clarify "timezone" flag on DateTime

Issue #2326 resolved
Former user created an issue

The DateTime column allows a timezone to be specified. This is ignored in the sqlite dialect. The problem caused by this is that you can store a timezone-aware datetime but then receive a naive datetime back causing issues when doing comparisons (e.g. in testing where you might be using an sqlite database in place of a different engine).

Attached patch will ensure that any timezone-aware datetimes are converted to the correct timezone before being stored and that the correct timezone is attached to any datetimes being retrieved from the database.

Comments (2)

  1. Mike Bayer repo owner

    oops - that's not what the "timezone" flag is for and this was not documented - that is fixed in 25f77454bdbfbe994eeb92a9824f135a603a0776. The flag is only to emit the TIMESTAMP WITH TIMEZONE directive on backends like PG which support it.

    The recipe you're looking for is:

    class TZNormalizedDateTime(TypeDecorator):
        impl = DateTime
    
        def __init__(self, timezone):
            self.timezone = timezone
            super(TZNormalizedDateTime, self).__init__()
    
        def process_bind_param(self, value, dialect):
            if value is not None and value.tzinfo:
                value = value.astimezone(self.timezone)
            return value
    
        def process_result_value(self, value, dialect):
            if value is not None:
                value = value.replace(tzinfo=self.timezone)
            return value
    

    if you think it would help, this recipe and some docs can also be added to the recipes at http://www.sqlalchemy.org/docs/core/types.html#typedecorator-recipes.

  2. Log in to comment