我看到在postgresql中我们可以将datetime转换为timestamp
或timestamptz
,即TIMESTAMP WITHOUT TIME ZONE
或TIMESTAMP 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