'Python/Sqlalchemy/Sqlite - How to select time zone aware datetimes from sqlite (or any other) database?

In sqlalchemy/sqlite I have a table defined as this:

class MyTable(Base):
    __tablename__ = 'mytable'
    ...
    field_dt = Column(DateTime)

Whenever I retrieve the record I have to do something like this in order to make it time zone aware:

row.field_dt.replace(tzinfo=dt.timezone.utc) # import datetime as dt

Can I somehow set something at table or field level that will apply tzinfo for each selected datetime from database?



Solution 1:[1]

One possibility would be to simply add a @property to your class:

class MyTable(Base):
    __tablename__ = 'mytable'
    id = Column(Integer, primary_key=True, autoincrement=False)
    field_dt = Column(DateTime)  # naive, saved as UTC

    @property
    def field_dt_aware(self):
        return self.field_dt.replace(tzinfo=dt.timezone.utc)


mt = MyTable(id=1, field_dt=dt.datetime(2022, 2, 22, 3, 4, 5))
print(mt.field_dt)  # 2022-02-22 03:04:05
print(mt.field_dt_aware)  # 2022-02-22 03:04:05+00:00

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gord Thompson