Search code examples
sqlpostgresqldatetimerounding

Query to round up timestamp to nearest 10 minutes


I am trying to round up a timestamp to the next full 10 minutes.
I have tried below solutions but wasn't able to get my expected results

I also tried date_trunc(), but couldn't make it work.

Expected results:

input expected output
2023-07-01 10:00:00 2023-07-01 10:10:00
2023-07-01 10:00:01 2023-07-01 10:10:00
2023-07-01 10:01:00 2023-07-01 10:10:00
2023-07-01 10:05:00 2023-07-01 10:10:00
2023-07-01 10:09:59 2023-07-01 10:10:00

Solution

  • Here is a way to do it :

    select dtime,
           (date_trunc('hour', dtime) +
            (cast(extract(minute from dtime) as int)/10 + 1) * 10 * interval '1 minute' 
           ) as rounded_dtime
    from mytable
    

    Demo here