将字符串转换为日期 postgresql

casting string to date postgresql

使用 postgres 14

我有一个类似于 2011-04-26T05:04:11Z 的时间戳。它在 UTC 时间 我尝试使用此函数将其转换为 postgres 时间戳,但我得到了错误的结果 2022-04-26 00:04:11-07。时间部分似乎搞砸了。

这是我的查询

select to_TIMESTAMP('2011-04-26T05:04:11Z','YYYY-MM-DDTHH:MI:SS')

如果您只想将字符串转换为 Postgres 时间戳,则:

select '2011-04-26T05:04:11Z'::timestamptz; 
04/25/2011 22:04:11 PDT

输出将取决于 DateStyle 设置。

为了使您的示例正常工作:

select to_TIMESTAMP('2011-04-26T5:04:11Z','YYYY-MM-DD"T"HH24:MI:SS');
      to_timestamp       
-------------------------
 04/26/2011 05:04:11 PDT

请注意 "T" 这会导致它被忽略,因为这似乎是导致问题的原因。不确定,但可能与使用 space 而不是 T 的 Postgres ISO 格式有关。要忽略的引用字符来自 Formatting function:

Tip

Prior to PostgreSQL 12, it was possible to skip arbitrary text in the input string using non-letter or non-digit characters. For example, to_timestamp('2000y6m1d', 'yyyy-MM-DD') used to work. Now you can only use letter characters for this purpose. For example, to_timestamp('2000y6m1d', 'yyyytMMtDDt') and to_timestamp('2000y6m1d', 'yyyy"y"MM"m"DD"d"') skip y, m, and d.

to_timestamp 中没有提供时区缩写,因此 Z 将被忽略,时间戳将采用具有相同时间值的本地时间。这就是为什么我使用 timestamptz cast 提出第一个建议的原因。

两种时区处理方式:

一个:

select to_TIMESTAMP('2011-04-26T5:04:11Z','YYYY-MM-DD"T"HH24:MI:SS')::timestamp AT time zone 'UTC';
        timezone         
-------------------------
 04/25/2011 22:04:11 PDT

两个:

select to_TIMESTAMP('2011-04-26T5:04:11+00','YYYY-MM-DD"T"HH24:MI:SS+TZH');
      to_timestamp       
-------------------------
 04/25/2011 22:04:11 PDT