将时间戳转换为 SQL 中的当前时间格式

convert timestamp to current time format in SQL

我有一个时间戳列,其值采用以下格式:

2021-07-20T18:40:36.368126186Z

我想将结果转换为干净的时间戳(24 小时格式):

2021-07-20 18:40:36

我尝试使用 DATE 字段,但它只给我日期,而 DATETIME 函数在我的数据库上不起作用。

select timestamp,
DATE(timestamp),
CURRENT_TIMESTAMP(0) AT TIME ZONE 'America/New_York'  
from  table

-- This doesn't work for now as the DATE method removes the time.

我为输出选择的格式类似于 CURRENT_TIMESTAMP(0) AT TIME ZONE 'America/New York'。我怎样才能得到它。我可以使用正则表达式只删除不需要的值吗?

我得到了答案:

SELECT timestamp AS original_ts, 
to_timestamp(REPLACE(REPLACE(timestamp,'T',' '),'Z',''),'YYYY-MM-DD HH:MI:SS') 
AS modified_ts from table

我也尝试使用 TO_TIMESTAMP_TZ 方法进行 CAST,但它没有按预期工作。如果有更好的解决方案,我很高兴知道,但现在我得到了答案。

只需删除传入字符串末尾的 'Z' 并将其转换为没有秒小数的时间戳。

WITH
indata(string) AS (
  SELECT '2021-07-20T18:40:36.368126186Z'
)
SELECT
  REPLACE(string,'Z','')::TIMESTAMP(0) AS resulting_timestamp_0
FROM indata;
 resulting_timestamp_0 
-----------------------
 2021-07-20 18:40:36
(1 row)