如何在更新中的 postgres 中将 bigint 转换为带时区的时间戳

bre*_*ttu 8 sql postgresql datetime

有没有办法将 a 投射BIGINT到PostgresTIMESTAMPTIMESTAMP WITH TIME ZONE在 Postgres 中?我需要将数据从BIGINT列复制到TIMESTAMP列。

这是我尝试过的:

update table
set date__timestamp = date__bigint::timestamp 
where foo = 1;
Run Code Online (Sandbox Code Playgroud)

错误:无法将 bigint 类型强制转换为没有时区的时间戳

我将时间戳列更改为带时区列并尝试了以下操作:

update table
set date__timestamp = date__bigint::timestamp with time zone at time zone 'PST' 
where foo = 1;
Run Code Online (Sandbox Code Playgroud)

错误:无法将 bigint 类型转换为带时区的时间戳

update table
set date__timstamp = TO_CHAR(TO_TIMESTAMP(date__bi / 1000), 'DD/MM/YYYY HH24:MI:SS')
where foo = 1;
Run Code Online (Sandbox Code Playgroud)

错误:“date__timestamp”列的类型是没有时区的时间戳,但表达式的类型是文本 提示:您需要重写或转换表达式。

数据看起来像这样。

date_bigint: 20181102
date_timestamp: 2018-11-02 17:00:00.000000
Run Code Online (Sandbox Code Playgroud)

我需要将默认值传递给铸造吗?

Kau*_*yak 11

您可以将其TO_TIMESTAMP转换为文本并使用并转换为timestamp at time zone

SELECT 
to_timestamp ( '20181102'::bigint::text,'YYYYMMDD')::timestamp at time zone 'UTC' 
at time zone 'PST' ;

update t
   set date__timestamp = TO_TIMESTAMP(date_bigint::text,'YYYYMMDD')::timestamp 
   at time zone 'UTC' at time zone 'PST'
where foo = 1;
Run Code Online (Sandbox Code Playgroud)

演示


Tim*_*sen 5

此答案假设该date__bigint列存储自纪元以来以秒为单位的 UNIX 时间戳。以下是转换为 Postgres 时间戳的一种方法:

UPDATE your_table
SET date__timestamp = TIMESTAMP 'epoch' + date__bigint * INTERVAL '1 second'
WHERE foo = 1;
Run Code Online (Sandbox Code Playgroud)

也就是说,我们可以在纪元时间戳中添加一些秒数,以将您的值转换为正式的 Postgres 时间戳。