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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With