Postgres: how do you round a timestamp up or down to the nearest minute?

前端 未结 4 1293
星月不相逢
星月不相逢 2020-12-14 13:37

Is there a postgresql function that will return a timestamp rounded to the nearest minute? The input value is a timestamp and the return value should be a timestamp.

4条回答
  •  盖世英雄少女心
    2020-12-14 14:18

    In trying to use Peter's answer above to create ceiling and floor functions I found that you have to take into account the seconds too when calling the rounding function. This here are my sets of functions that will round, floor, and ceiling timestamps.

    CREATE OR REPLACE FUNCTION round_minutes( TIMESTAMP WITHOUT TIME ZONE, integer) 
    RETURNS TIMESTAMP WITHOUT TIME ZONE AS $$ 
      SELECT date_trunc('hour', $1) + (cast(($2::varchar||' min') as interval) * round( (date_part('minute',$1)::float + date_part('second',$1)/ 60.)::float / cast($2 as float)))
    $$ LANGUAGE SQL IMMUTABLE STRICT;
    
    CREATE OR REPLACE FUNCTION floor_minutes( TIMESTAMP WITHOUT TIME ZONE, integer ) 
    RETURNS TIMESTAMP WITHOUT TIME ZONE AS $$ 
        SELECT round_minutes( $1 - cast((($2/2)::varchar ||' min') as interval ), $2 );
    $$ LANGUAGE SQL IMMUTABLE STRICT;
    
    CREATE OR REPLACE FUNCTION ceiling_minutes( TIMESTAMP WITHOUT TIME ZONE, integer ) 
    RETURNS TIMESTAMP WITHOUT TIME ZONE AS $$ 
        SELECT round_minutes( $1 + cast((($2/2)::varchar ||' min') as interval ), $2 );
    $$ LANGUAGE SQL IMMUTABLE STRICT;
    

提交回复
热议问题