PostgreSQL: format interval as minutes

后端 未结 3 1112
时光取名叫无心
时光取名叫无心 2020-12-29 19:31

When I subtract timestamps, the interval is in form DD:HH:MM:SS. How can I convert it all to minutes without extracting days and hours and multiplication/addition

3条回答
  •  时光取名叫无心
    2020-12-29 20:05

    As a previous answer points out, the trick is to convert the interval to an "epoch", that is, an absolute number of seconds, and then divide appropriately for absolute numbers of other units.

    Sone years ago, I wrote an interval_convert function which generalises this to most of the arguments accepted by date_part, assuming that a month is 30 days, and a year is 365.25 days.

    Feel free to use and modify as you see fit:

    CREATE FUNCTION 
        interval_convert(in_unit text, in_interval interval) 
        RETURNS double precision
    AS $FUNC$
        SELECT
            EXTRACT(
                EPOCH FROM
                $2 -- in_interval 
            )
            /
            -- Slightly lazy way of allowing both singular and plural
            --  has side effect that 'centurie' and 'centurys' are accepted
            --  but otherwise behaves similarly to DATE_TRUNC
            CASE TRIM(TRAILING 's' FROM LOWER(
                $1 -- in_unit
            ))
                WHEN 'microsecond'  THEN 0.000001 
                WHEN 'millisecond'  THEN 0.001
                WHEN 'second'       THEN 1
                WHEN 'minute'       THEN 60
                WHEN 'hour'         THEN 3600
                WHEN 'day'          THEN 86400
                WHEN 'week'         THEN 604800
                WHEN 'month'        THEN 2592000 -- 30 days
                -- WHEN 'quarter'      THEN -- Not supported
                WHEN 'year'         THEN 31557600 -- 365.35 days
                WHEN 'decade'       THEN 315576000
                WHEN 'century'      THEN 3155760000
                WHEN 'centurie'     THEN 3155760000
                WHEN 'millennium'   THEN 31557600000
                WHEN 'millennia'    THEN 31557600000
            END
    $FUNC$
        LANGUAGE sql 
        IMMUTABLE 
        RETURNS NULL ON NULL INPUT;
    

提交回复
热议问题