2

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?

user3225309
  • 1,183
  • 3
  • 15
  • 31
  • I am also following up with this question. Is there a better way to avoid replacing the tzinfo of each returned row one by one – adam Jul 26 '23 at 14:58

1 Answers1

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
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
  • Can I avoid having a field and property because I would always like to get tz aware datetime. I saw somethin like this colum definition: sa.Column('date', sa.types.DateTime(timezone=True), default=datetime.datetime.utcnow) on https://stackoverflow.com/questions/414952/sqlalchemy-datetime-timezone. Do you have any experience with this approach? – user3225309 Mar 04 '22 at 00:47