在 postgresql 函数中使用 unix 时间戳

Using unix time stamp in postgresql functions

我有一个程序可以在我的 postgresql tables 中插入日期。这是一个很长的查询,处理 8 table,但问题是它在正常日期下工作正常,但我需要放置 unix 时间戳。我已经尝试了一些解决方案,但仍然无法弄清楚。以下是我的功能。

CREATE OR REPLACE FUNCTION public.insert_date(responsetime integer, 
responsetimestamp time with time zone)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
    DECLARE
        responsetime integer;
    INSERT INTO data(responsetime, dim_date_id) VALUES (responsetime, 
 CAST( to_char(responsetimestamp, 'YYYYMMDD') as INT))
SELECT INTO data_id currval('data_id_seq');
RETURN data_id;
;

使用以下命令可以正常工作

select insert_data(
457,
'2021-06-30T05:16:50+00:00');

但是我想在其中使用时间戳

select insert_data(
457,
1624978969607);

我也尝试过将参数类型更改为整数,但它不起作用。

如果您想使用 Postgres timestamp 字段,则需要使用 timestamp 值。 Unix 纪元不是可以直接存储在 timestamp 字段中的值。消除 CAST 并只存储实际的时间戳值。然后,如果您想要检索数据时的 EPOCH 值,请执行以下操作:


select extract(epoch from '06/30/21 12:58:32'::timestamp);
 date_part  
------------
 1625057912
(1 row)

--In milliseconds as show

select extract(epoch from '06/30/21 12:58:32'::timestamp) * 1000;
   ?column?    
---------------
 1625057912000

更新 毫秒级。

如果您想直接使用整数值,您可以从这里使用 to_timestamp(Unix epoch in seconds)

https://www.postgresql.org/docs/current/functions-datetime.html

由于您的值看起来以毫秒为单位,因此您需要执行以下操作:

select to_timestamp(1624978969607/1000);

将值返回到秒。