SQLAlchemy cast to PostgreSQL TIMESTAMP WITH TIME ZONE



我看到在postgresql中我们可以将datetime转换为timestamptimestamptz,即TIMESTAMP WITHOUT TIME ZONETIMESTAMP WITH TIME ZONE

例如使用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