【问题标题】:Add hours to date to achieve next 6:00添加小时到日期以实现下一个 6:00
【发布时间】:2020-09-01 18:37:20
【问题描述】:

我有 TIMESTAMP,我想修改这个时间戳以在下一个早上 6 点创建新的时间戳。 例如

2020-09-01 22:00:00 -> 2020-09-02 06:00:00
2020-08-30 04:00:00 -> 2020-08-30 06:00:00

知道一步是否可行吗?

现在我有伪代码,例如:

hour = extract(hour from mytimestamp)
if hour > 0 and hour < 7 then
  date_trunc('hour', mytimestamp) + interval 6-hour
else
  date_trunc('day', mytimestamp) + interval '1 day' + interval '6 hours'
end if;

【问题讨论】:

    标签: sql postgresql date


    【解决方案1】:

    您可以使用 CASE 表达式来做到这一点:

    select case 
             when the_column::time > time '07:00' then (the_column::date + 1) + time '06:00'
             else the_column::date + time '06:00'
           end as new_column
    from the_table
    

    the_column::date 将时间戳转换为日期(没有时间)。然后将所需时间简单地添加到该日期以获取新时间戳。要获得第二天,使用+1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      相关资源
      最近更新 更多