postgresql - 如何将字符串视为 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。
解决方案
的返回类型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)
推荐阅读
- python - 如何在 Windows 中设置 OS 密钥以便稍后在 Python 中访问它?
- python - 试图找到具有最大第一个元素的数组?
- sql - 为过程 PLSQL 创建自己的异常
- c# - 在 C# 中更新矩阵类实例的值
- javascript - 在 React 中为视频元素设置音量
- python - Seaborn 分裂小提琴情节未正确分裂
- python - 具有多个特征的递归神经网络中的错误
- javascript - 即使我使用的是 :not 选择器,也会触发事件侦听器
- c# - BigInteger 上的十六进制
- ios - 初始化程序 'init(_:)' 要求 '(UITextRange) -> String?' 符合 'BinaryInteger'