【问题标题】:How to treat string as UTC timestamp?如何将字符串视为 UTC 时间戳?
【发布时间】:2019-06-08 07:48:29
【问题描述】:

我必须读取像 '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。

【问题讨论】:

    标签: postgresql timezone


    【解决方案1】:

    TO_TIMESTAMP 的返回类型是timestamp 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)
    

    【讨论】:

    • 我已经很亲近了……谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-03-14
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2021-07-24
    • 2016-10-11
    相关资源
    最近更新 更多