How to round to nearest X minutes with PL/pgSQL?

后端 未结 7 1470
伪装坚强ぢ
伪装坚强ぢ 2021-01-07 03:36

How I can round to nearest X minutes?

Here\'s my attempt:

DECLARE
  _stamp ALIAS FOR $1; -- timestamp
  _nearest ALIAS FOR $2; -- minutes (integer)
         


        
相关标签:
7条回答
  • 2021-01-07 04:09

    You can do it as a simple SQL statement, substitute CURRENT_TIMESTAMP with your TIMESTAMP value.

    SELECT date_trunc('minute', CURRENT_TIMESTAMP::timestamp without time zone)
        + (
        CASE WHEN extract(second from CURRENT_TIMESTAMP ) >= 30
            THEN 1::text
            ELSE 0::text
        END
        || ' minute'
    
        )::interval ;
    

    An optimization, would be adding 30 seconds and then just doing date_trunc(), I knew this before but special thanks irc://irc.freenode.net/#postgresql's StuckMojo

    SELECT date_trunc(
        'minute'
        , CURRENT_TIMESTAMP::timestamp without time zone
          + '30 seconds'::interval
    );
    

    update @stephen, sure it does -- even though technically speaking that isn't what the question called for.

    CREATE OR REPLACE FUNCTION round_trunc ( in text, in timestamp ) RETURNS timestamp without time zone  AS $$
      SELECT pg_catalog.date_trunc(
          $1
          , $2::timestamp without time zone
            + ('0.5 ' || $1 )::interval
      )
    $$ LANGUAGE sql VOLATILE;
    

    Oh wait, I see what he is asking for, he wants to round to the nearest abstract sub-unit of time. Like a quarter hour, I'm way off here.

    0 讨论(0)
提交回复
热议问题