【问题标题】:How can postgres change from unix epoch time with miliseconds to timestamptz?postgres 如何从毫秒的 unix 纪元时间更改为 timestamptz?
【发布时间】:2021-04-24 22:16:44
【问题描述】:

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

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

epoch 时间不包含毫秒时有效,但包含毫秒时无效。以下查询:

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

返回:

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

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    As documented in the manual 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
    

    【讨论】:

    • 所以毫秒部分总是148ms。我不是 100% 确定计算纪元时间的复杂性如何工作,但给定的纪元值是否表示 148 毫秒?
    • @Mistu4u: 是的(但你需要将值转换为double 否则它是一个整数除法。这是你不应该在其中存储“epoch”值的众多原因之一开始的数据库。
    • 一个有趣的阅读:Epoch Mania.
    猜你喜欢
    • 2021-06-11
    • 2022-10-13
    • 1970-01-01
    • 2011-03-24
    • 2012-03-08
    • 2023-03-27
    • 2012-02-19
    • 2012-01-10
    • 2012-10-18
    相关资源
    最近更新 更多