首页 > 解决方案 > 如何将字符串视为 UTC 时间戳?

问题描述

我必须读取像 '20190608070000' 这样的字符串作为 UTC 给出的时间戳。有没有简单的方法可以做到这一点?

这个采用 UTC 但需要格式化输入:

postgres=# show time zone;
 TimeZone
----------
 CET
(1 Zeile)

postgres=# select timestamp without time zone '2019-06-08 07:00:00' at time zone 'UTC';
        timezone
------------------------
 2019-06-08 09:00:00+02
(1 Zeile)

据我所知, to_timestamp() 总是将所有输入视为本地时间,因此输出以错误的方式移动:

postgres=# SELECT to_timestamp('20190608070000', 'YYYYMMDDHH24MISS') AT time zone 'UTC';
      timezone
---------------------
 2019-06-08 05:00:00
(1 Zeile)

实际上我使用的是 PostgreSQL 9.6。

标签: postgresqltimezone

解决方案


的返回类型TO_TIMESTAMPtimestamp with time zone。显示的时间是您当前会话的时区(带有 UTC 偏移量)。

SET SESSION timezone TO 'CET';
SET
knayak=# SELECT to_timestamp('20190608070000', 'YYYYMMDDHH24MISS');
      to_timestamp
------------------------
 2019-06-08 07:00:00+02

当您使用 转换它时AT TIME ZONE,它将07:00在您当前时区的小时内显示 UTC 时间。

SELECT to_timestamp('20190608070000', 'YYYYMMDDHH24MISS') AT time zone 'UTC';
      timezone
---------------------
 2019-06-08 05:00:00
(1 row)

因此,如果您希望以所需格式读取时间戳并将其视为 UTC,请将输出to_timestamp显式转换为timestamp(无时区),然后应用AT TIME ZONE.

SELECT to_timestamp('20190608070000', 'YYYYMMDDHH24MISS') :: timestamp 
    AT time zone 'UTC';

        timezone
------------------------
 2019-06-08 09:00:00+02
(1 row)

推荐阅读