I’m using sqlmodel
to do sql-orm. I learned from this page and this page, but both failed, the time inserted into the table is anyway utc time, no matter I set timezone
True or False. At last I need to set cur_time: str = Field(default=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
then everything goes well. But I’m just confused why I can’t insert local time with Columns(DateTime(timezone=True))
My code is
from datetime import datetime
from sqlmodel import (
TIMESTAMP,
Column,
DateTime,
Field,
Session,
SQLModel,
create_engine,
func,
text,
)
class Test(SQLModel, table=True):
__tablename__ = "test"
id: int | None = Field(default=None, primary_key=True)
name: str
# 1st page, utc time
first_time: datetime | None = Field(
sa_column=Column(
TIMESTAMP(timezone=True),
nullable=False,
server_default=text("CURRENT_TIMESTAMP"),
)
)
# 2nd page, utc time
second_time: datetime | None = Field(
sa_column=Column(DateTime(timezone=True), server_default=func.now())
)
# datetime.now, local time
third_time: str = Field(default=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
uri = "sqlite:///./test.db"
engine = create_engine(uri, echo=True)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
test = Test(name="test")
session.add(test)
session.commit()
And the result is
I’m using sqlmodel 0.0.20, sqlalchemy 2.0.31, python 3.10.12. I tried both on win10 and ubuntu 22.04, and results are the same, things only go well when I use datetime.now().strftime
.
On ubuntu, timedatectl
‘s result is
Local time: Fri 2024-07-19 15:04:41 CST
Universal time: Fri 2024-07-19 07:04:41 UTC
RTC time: Fri 2024-07-19 07:04:42
Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: yes
NTP service: active
RTC in local TZ: no