Python SqlAlchemy使用PostgreSQL时间戳;“在时区”;询问中
我有一个PostgreSQL 11表,其中有一列类型为带时区的时间戳,我想在不同的时区中显示这个时间。在纯PL/pgSQL中,我可以编写如下查询Python SqlAlchemy使用PostgreSQL时间戳;“在时区”;询问中,python,postgresql,sqlalchemy,timestamp-with-timezone,Python,Postgresql,Sqlalchemy,Timestamp With Timezone,我有一个PostgreSQL 11表,其中有一列类型为带时区的时间戳,我想在不同的时区中显示这个时间。在纯PL/pgSQL中,我可以编写如下查询 select id, creation_date at timezone 'America/New_York' from "Test" where id=1; 这就把所有讨厌的时区处理留给了数据库。 现在,如果我在SqlAlchemy中映射表(使用版本1.4.5): 我可以使用例如 with Session(engine) as
select id, creation_date at timezone 'America/New_York' from "Test" where id=1;
这就把所有讨厌的时区处理留给了数据库。
现在,如果我在SqlAlchemy中映射表(使用版本1.4.5):
我可以使用例如
with Session(engine) as session:
test = session.scalar(select(Test).where(Test.id==1))
但这让我可以用UTC中的Pythondatetime
对象来测试.creation\u date。当然,我可以运行这个查询,然后用Python转换时区,但是在选择时是否可以告诉SqlAlchemy将时区“America/New\u York”的部分添加到Test.creation\u date
列?
编辑:美国/纽约只是一个例子,必须为每个查询设置实际时区。如果您需要在每个查询中指定时区,并且根据
函数timezone(zone,timestamp)
相当于符合SQL的构造时区时间戳
以下解决方案应适用于您:
from sqlalchemy import func
expr = func.timezone('America/New_York', Test.creation_date)
test, in_ny = (
session.query(
Test,
expr.label("in_ny"),
).filter(Test.id == 1)
).one()
你总是希望TZ是美国/纽约吗?或者在运行查询时是否需要配置它?将为每个查询配置它。为整个连接设置时区不会切断连接。
from sqlalchemy import func
expr = func.timezone('America/New_York', Test.creation_date)
test, in_ny = (
session.query(
Test,
expr.label("in_ny"),
).filter(Test.id == 1)
).one()