Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 999
user3225309 Avatar asked Oct 16 '25 06:10

user3225309


1 Answers

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
like image 91
Gord Thompson Avatar answered Oct 17 '25 19:10

Gord Thompson