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

PostgreSQL:如何将Unix时间戳转换为精确到分钟的timestamp类型?

Unix时间戳转精确到分钟的Timestamp类型方法

正确实现方式

直接使用date_trunc('minute', to_timestamp(你的Unix时间戳))即可得到timestamp类型的结果,完全符合需求。以示例时间戳1672718268为例,执行语句:

SELECT date_trunc('minute', to_timestamp(1672718268));

返回的timestamp值为2023-01-03 06:57:00(虽然显示带秒,但秒数固定为0,本质是已截断到分钟级别的timestamp类型)。

你可以用pg_typeof()函数验证返回类型:

SELECT pg_typeof(date_trunc('minute', to_timestamp(1672718268)));

结果会显示timestamp with time zone(或对应timestamp类型),证明不是字符串。

你尝试的方法问题分析

  • 第一个方法:to_timestamp(timemodified)::date + date_trunc('hour', timemodified) + date_part('minute', timemodified)::int
    类型拼接逻辑错误,date、timestamp和整数直接相加会触发语法错误,完全没必要用这种复杂且错误的方式拼接时间。
  • 第二个方法:to_timestamp(to_timestamp(timemodified)::timestamp,'YYYY-MM-DD HH24:MI')
    to_timestamp的第二个参数用于解析字符串,传入timestamp类型会导致类型不匹配,属于无用且错误的嵌套调用。
  • 第三个方法:extract(epoch from timemodified) from table
    这个语句是将timestamp类型转回Unix时间戳,和需求完全相反,无法实现转换到分钟级timestamp的目的。
  • 第四个方法:date_trunc('minute', to_timestamp(timemodified)::timestamp)
    这个写法本身是正确的!to_timestamp(timemodified)已经返回timestamp类型,后面的::timestamp属于多余的类型转换,但不影响最终结果。执行后得到的就是你需要的分钟级timestamp类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 03:52:47