You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PostgreSQL中以可读格式计算两个时间戳的差值

PostgreSQL计算Unix毫秒时间戳差值并格式化可读时长

我在PostgreSQL中有一张表,包含created_on和closed_on两列,存储的是Unix毫秒时间戳。需要计算这两个时间戳的差值,并以可读格式展示,例如1 year, 9 days, 1 hour, 6 minutes, 1 second。

初始表结构及数据

idcreated_onclosed_on
116548508340251687168395586

尝试的查询语句

SELECT 
    (closed_on - created_on) * interval '1 millisecond' as interval1,
    justify_interval(32317561561 * interval '1 millisecond') as interval2,
    to_timestamp(closed_on / 1000)::timestamp - to_timestamp(created_on / 1000)::timestamp as interval3,
    to_timestamp(created_on / 1000)::timestamp as created_on,
    to_timestamp(closed_on / 1000)::timestamp as closed_on
FROM test

查询返回结果

interval1interval2interval3created_onclosed_on
{"hours":8977,"minutes":6,"seconds":1,"milliseconds":561}{"years":1,"days":14,"hours":1,"minutes":6,"seconds":1,"milliseconds":561}{"days":374,"hours":1,"minutes":6,"seconds":1}2022-06-10T08:47:14.000Z2023-06-19T09:53:15.000Z

存在的问题

  • interval1仅显示小时,未展示天、月等单位
  • interval2错误显示14天,实际应为1年零9天
  • interval3天数正确,但未展示年、月单位

期望结果

1 year, 9 days, 1 hour, 6 minutes, 1 second

内容的提问来源于stack exchange,提问作者executable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 23:45:25