如何使SQLAlchemy生成AT TIME ZONE语法?

时间:2019-07-04 21:24:42

标签: postgresql sqlalchemy

我在Postgresql的timestamp without time zone列中有一个存储UTC日期时间的表:

      Column       |            Type             | Collation | Nullable |
-------------------+-----------------------------+-----------+----------+----
 ...
 start             | timestamp without time zone |           | not null | 
 end               | timestamp without time zone |           | not null | 

psql提示符下,我可以请求Postgres使用以下语法将日期转换为请求的时区:

SELECT (start::timestamp AT TIME ZONE 'UTC') AT TIME ZONE 'AEST' FROM ...

如何在SQLAlchemy中表达此语法?我无法在Python中进行转换,因为我将对该数据进行一些GROUP BY操作。

1 个答案:

答案 0 :(得分:0)

解决了这个问题!

    in_users_timezone = MyModel.start.op('AT TIME ZONE')('UTC').op('AT TIME ZONE')(users_time_zone)

    date_column = func.date_trunc('day', in_users_timezone).label('date')

    query = query.group_by(date_column)