我已经看到,在postgresql中,我们可以将日期时间转换为timestamp
或timestamptz
,即TIMESTAMP NOT TIME ZONE
或TIMESTAMP WITH时区
。
例如使用psql(Postgres shell)
:
db=# select '2023-03-31 00:00:00'::timestamp;
timestamp
---------------------
2023-03-31 00:00:00
或
db=# select '2023-03-31 00:00:00'::timestamptz;
timestamptz
------------------------
2023-03-31 00:00:00+00
第二个例子正是我想要用 SqlAlchemy 做的事情。
我知道我们可以使用 Model.created_date.cast(TIMESTAMP)
这就像第一个示例,但我需要将 created_date
转换为 timestamptz
.
这样做的目的是提取该日期在许多不同时区的某些部分。
另外,我的模型中的字段是这样的:
created_date = Column(DateTime, nullable=False, default=datetime.utcnow)
最佳答案
您可以将 timezone=True
传递给 PostgreSQL 的 TIMESTAMP
类型:
from sqlalchemy import create_engine, cast, select, text
from sqlalchemy.dialects.postgresql import TIMESTAMP
engine = create_engine("postgresql://…")
qry = select(cast(text("'2023-03-31 00:00:00'"), TIMESTAMP(timezone=True)))
print(qry.compile(engine))
# SELECT CAST('2023-03-31 00:00:00' AS TIMESTAMP WITH TIME ZONE) AS anon_1
关于python - SQLAlchemy 转换为带有时区的 PostgreSQL 时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75930570/