How to write bigint (timestamp in milliseconds) va

2019-04-04 19:42发布

I'm trying to store in timestamp with timezone field my value. It is in milliseconds from 1970.

select TO_CHAR(TO_TIMESTAMP(1401432881230), 'DD/MM/YYYY HH24:MI:SS.MS')

Expected 30/5/2014 11:29:42 10:54:41.230, but get 22/08/46379 23:27:02.000

3条回答
相关推荐>>
2楼-- · 2019-04-04 20:14

This is how I convert ms to timestamp and keep ms instead seconds.The accepted answer will drop ms.

WITH ts AS (SELECT 1401432881230 AS ts)
SELECT to_timestamp(ts / 1000) + ((ts % 1000 ) || ' milliseconds') :: INTERVAL
FROM ts;

-- FOR ALTER COLUMN
ALTER TABLE  my_info
  ALTER COLUMN tstmp TYPE TIMESTAMP USING to_timestamp(tstmp / 1000) + ((tstmp % 1000) || ' milliseconds') :: INTERVAL;
查看更多
神经病院院长
3楼-- · 2019-04-04 20:15

Unix timestamps measures time with seconds, and not milliseconds (almost everywhere, in PostgreSQL too).

Therefore you need to call

SELECT TO_TIMESTAMP(1401432881230 / 1000);

If you want to preserve milliseconds, call with double precision:

SELECT TO_TIMESTAMP(1401432881230::double precision / 1000);
查看更多
迷人小祖宗
4楼-- · 2019-04-04 20:21

Okay, I understood. My INSERT should looks like:

INSERT INTO events (timestamp) VALUES (to_timestamp(TO_CHAR(TO_TIMESTAMP(1401432881222 / 1000), 'YYYY-MM-DD HH24:MI:SS') || '.' || (1401432881222%1000), 'YYYY-MM-DD HH24:MI:SS.MS'))

I'm converting bigint-timestamp with milliseconds to text with required format ('YYYY-MM-DD HH24:MI:SS.MS') and pass it to to_timestamp function.

查看更多
登录 后发表回答