Postgresql圆形时间戳到最近的30秒

时间:2017-06-07 12:18:21

标签: sql postgresql

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

3 个答案:

答案 0 :(得分:4)

select to_timestamp( round( ( extract ('epoch' from ts) ) /30 ) * 30 )

答案 1 :(得分:2)

这是一种方法:

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 :(得分:0)

圆形上下文和下划线非常难看:

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