【问题标题】:Postgresql round timestamp to nearest 30 secondsPostgresql 将时间戳舍入到最接近的 30 秒
【发布时间】:2017-06-07 12:18:21
【问题描述】:

可以在 postgres 中将时间戳四舍五入到最近的 30 秒吗? 例如:

source -> result

2017-06-07 14:11:20 -> 2017-06-07 14:11:00
2017-06-07 14:11:40 -> 2017-06-07 14:11:30
2017-06-07 14:12:10 -> 2017-06-07 14:12:00

【问题讨论】:

  • 2017-06-07 14:11:50 -> 2017-06-07 14:12:00?..

标签: sql postgresql


【解决方案1】:

这是一种方法:

select (date_trunc('minute', ts) +
        (case when extract(second from ts) > 30 then 30 else 0 end) * interval '1 second' 
       ) as rounded_ts

注意:向下取整 30 秒。

【讨论】:

    【解决方案2】:
    select to_timestamp( round( ( extract ('epoch' from ts) ) /30 ) * 30 )
    

    【讨论】:

    • 那应该是to_timestamp() 而不是timestamp(): to_timestamp(round( extract('epoch' from ts) / 30 ) * 30) 那么它工作得很好。 (虽然接受的答案没有四舍五入到最近的 30 秒。)我已经相应地编辑了答案。
    • 我猜你应该使用 floor 而不是 round
    【解决方案3】:

    向上和向下四舍五入非常难看:

    t=# with a(ts) as (
      values ('2017-06-07 14:11:20'::timestamp),('2017-06-07 14:11:40'),('2017-06-07 14:12:10'),('2017-06-07 14:11:50')
    )
    , c as (
      select *,date_trunc('minute',ts) t0, date_trunc('minute',ts) + '15 seconds'::interval t1,date_trunc('minute',ts)+ '30 seconds'::interval t2,date_trunc('minute',ts)+ '45 seconds'::interval t3, date_trunc('minute',ts) + '1 minute'::interval t5
      from a
    )
    select case when ts between t0 and t1 then t0 when ts between t1 and t3 then t2 when ts between t3 and t5 then t5 end rnd,ts from c;
             rnd         |         ts
    ---------------------+---------------------
     2017-06-07 14:11:30 | 2017-06-07 14:11:20
     2017-06-07 14:11:30 | 2017-06-07 14:11:40
     2017-06-07 14:12:00 | 2017-06-07 14:12:10
     2017-06-07 14:12:00 | 2017-06-07 14:11:50
    (4 rows)
    
    Time: 0.434 ms
    

    【讨论】:

      猜你喜欢
      • 2018-10-25
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 2017-12-02
      • 2021-05-07
      • 2018-05-27
      • 2014-12-12
      相关资源
      最近更新 更多