【发布时间】:2021-03-17 03:28:21
【问题描述】:
at time zone 运算符在 date 类型上的行为与 PostgreSQL 中的预期不同。
set time zone 'UTC';
select
'2021-01-03'::date at time zone 'America/Chicago' as "value",
pg_typeof('2021-01-03'::date at time zone 'America/Chicago') as "type";
| x | value | type |
|---|---|---|
| Expected | 2021-01-03 06:00:00+00 | timestamp with time zone |
| Actual | 2021-01-02 18:00:00 | timestamp without time zone |
在 PostgreSQL 服务器版本 10、11、12 和 13 上测试。
这种行为对我来说很奇怪,我无法找到任何描述或讨论它的地方。似乎 PSQL 隐式地将date 转换为timestamptz(使用系统时区),然后应用at time zone 运算符。我知道 at time zone 运算符仅(在文档中)为 timestamp(tz) 和 time(tz) 类型定义。但是,我会假设 PSQL 会将 date 隐式转换为 timestamp 而不是 timestamptz,因为:
- 这是一种“安全”转换(无需假设时区)。只需附加
00:00:00。 - 它会产生
timestamptz,当在没有时区的类型上使用at time zone运算符时会出现这种情况。
当前的行为对我来说根本没有意义,我想不出一个可以从中受益的用例。您要求 timestamp with time zone 获取特定时区的日期,而您却得到了本地化到给定时区的系统时区日期的 timestamp。
当然,一个简单的解决方法是先转换为timestamp:
set time zone 'UTC';
select '2021-01-03'::date::timestamp at time zone 'America/Chicago';
我希望有人能对此有所了解。我错过了什么?也许一些关于如何将date 隐式转换为timestamp(tz) 的总体规则?这种行为是否记录在某处?
谢谢!
- 迈克
【问题讨论】:
标签: postgresql date datetime