PostgreSQL(9.6.5)在没有时区的时区之间转换返回时间戳

时间:2018-01-31 02:39:42

标签: sql postgresql sqldatatypes

让我们从测试表开始:

CREATE TABLE test
(
    ts_tz timestamp with time zone
);

让我们插入一行数据:

INSERT INTO
    test (ts_tz)
VALUES
    (TIMESTAMP WITH TIME ZONE '2016-08-12 10:22:31.949271-00')
;

现在,让我们查询这一行:

postgres=# select * from test;
             ts_tz             
-------------------------------
 2016-08-12 03:22:31.949271-07

好的,到目前为止,这对我来说很有意义。 ts_tz是带时区的时间戳,它显示为03:22,偏移量为-07,因为这就是我的时区。

现在,假设我想将时区更改为“美国/太平洋地区”。

postgres=# select ts_tz AT TIME ZONE 'US/Pacific' from test;
          timezone          
----------------------------
 2016-08-12 03:22:31.949271 

但是现在这会返回一个没有时区的TIMESTAMP。

这是为什么?如何将其保留为时区的TIMESTAMP?

1 个答案:

答案 0 :(得分:1)

这就是AT TIME ZONE构建工作的方式 - timestamptz变为timestamp without timezone,反之亦然:

https://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT enter image description here

如果您希望timestamp with zone在指定的某个时区使用SET,例如:

t=# set timezone to 'EST';
SET
t=#  select * from test;
             ts_tz
-------------------------------
 2016-08-12 05:22:31.949271-05
(1 row)
相关问题