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

如何在PostgreSQL中插入当日指定小时的Timestamp?

在PostgreSQL中实现当日指定小时的DateTime插入

嘿,这个需求在PostgreSQL里其实有好几种简洁的实现方式,我给你列几个常用的方案:

方案1:最简洁的写法(推荐)

利用current_date获取当日日期(不带时间部分),直接加上指定的小时间隔即可:

INSERT INTO sessions VALUES(current_date + interval '12 hours', 1, 1);

current_date会返回类似2024-05-20的日期值,加上interval '12 hours'后会自动转换为2024-05-20 12:00:00的timestamp类型,完美匹配你的需求。

方案2:类似SQL Server的构造函数写法

PostgreSQL提供了make_timestamp函数,和SQL Server的SMALLDATETIMEFROMPARTS逻辑类似,通过指定年、月、日、时、分、秒来构造时间:

INSERT INTO sessions VALUES(
  make_timestamp(
    extract(year from current_date)::integer,
    extract(month from current_date)::integer,
    extract(day from current_date)::integer,
    12,
    0,
    0.0
  ),
  1,
  1
);

这里用extract函数提取当前日期的年、月、日并转为整数,再指定12点0分0秒,最终得到当日12点整的时间。

方案3:截断当前时间后叠加小时

也可以先把当前时间截断到当日0点,再加上指定小时:

INSERT INTO sessions VALUES(date_trunc('day', current_timestamp) + interval '12 hours', 1, 1);

date_trunc('day', current_timestamp)会得到当日0点的timestamp值,加上12小时后就得到12点整的时间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:04:32