首页 > 解决方案 > postgres 如何从以毫秒为单位的 unix 纪元时间更改为 timestamptz?

问题描述

我正在使用下面的 postgres sql 将 unix 纪元时间转换为时间戳。

select to_timestamp(1608816600) at time zone 'UTC';

它在纪元时间不包含毫秒时起作用,但当它包含毫秒时,它不起作用。以下查询:

select to_timestamp(1611150788148) at time zone 'UTC';

返回:

在此处输入图像描述

然而,它应该是Wed Jan 20 2021 13:53:08和几毫秒。来源:https ://currentmillis.com/

标签: postgresql

解决方案


如手册中所述, to_timestamp()预计“自 1970-01-01 00:00:00+00 以来的秒数” - 但它允许小数值。

如果要指定毫秒,则需要将值除以 1000

select to_timestamp(1611150788148::double precision/1000) at time zone 'UTC';

select to_char(to_timestamp(1611150788148/1000.0) at time zone 'UTC', 'yyyy-mm-dd hh24:mi:ss.ff3');

to_char                
-----------------------
2021-01-20 13:53:08.148

推荐阅读