Count months between two timestamp on postgresql?

前端 未结 11 1147
一个人的身影
一个人的身影 2021-02-01 14:50

I want to count the number of months between two dates.

Doing :

SELECT TIMESTAMP \'2012-06-13 10:38:40\' - TIMESTAMP \'2011-04-30 14:38:40\';


        
相关标签:
11条回答
  • 2021-02-01 15:10

    If you will do this multiple times, you could define the following function:

    CREATE FUNCTION months_between (t_start timestamp, t_end timestamp)
        RETURNS integer
        AS $$
            SELECT
                (
                    12 * extract('years' from a.i) + extract('months' from a.i)
                )::integer
            from (
                values (justify_interval($2 - $1))
            ) as a (i)
        $$
        LANGUAGE SQL
        IMMUTABLE
        RETURNS NULL ON NULL INPUT;
    

    so that you can then just

    SELECT months_between('2015-01-01', now());
    
    0 讨论(0)
  • 2021-02-01 15:13

    Try;

    select extract(month from  age('2012-06-13 10:38:40'::timestamp, '2011-04-30 14:38:40'::timestamp)) as my_months; 
    
    0 讨论(0)
  • 2021-02-01 15:16

    I had the same problem once upon a time and wrote this ... it's quite ugly:

    postgres=>  SELECT floor((extract(EPOCH FROM TIMESTAMP '2012-06-13 10:38:40' ) - extract(EPOCH FROM TIMESTAMP '2005-04-30 14:38:40' ))/30.43/24/3600);
     floor 
    -------
        85
    (1 row)
    

    In this solution "one month" is defined to be 30.43 days long, so it may give some unexpected results over shorter timespans.

    0 讨论(0)
  • 2021-02-01 15:16

    Extract by year and months will floor on months:

    select extract(year from age('2016-11-30'::timestamp, '2015-10-15'::timestamp)); --> 1
    select extract(month from age('2016-11-30'::timestamp, '2015-10-15'::timestamp)); --> 1
    --> Total 13 months
    

    This approach maintains fractions of months (thanks to tobixen for the divisor)

    select round(('2016-11-30'::date - '2015-10-15'::date)::numeric /30.43, 1); --> 13.5 months
    
    0 讨论(0)
  • 2021-02-01 15:20

    Gives the differenece of months of two dates

       SELECT ((extract( year FROM TIMESTAMP '2012-06-13 10:38:40' ) - extract( year FROM TIMESTAMP '2011-04-30 14:38:40' )) *12) + extract(MONTH FROM TIMESTAMP '2012-06-13 10:38:40' ) - extract(MONTH FROM TIMESTAMP '2011-04-30 14:38:40' );
    

    The Result : 14

    Have to extract months seperately for both the dates and then the difference of both the results

    0 讨论(0)
  • 2021-02-01 15:30

    The age function give a justified interval to work with:

    SELECT age(TIMESTAMP '2012-06-13 10:38:40', TIMESTAMP '2011-04-30 14:38:40');
    

    returns 1 year 1 mon 12 days 20:00:00, and with that you can easily use EXTRACT to count the number of months:

    SELECT EXTRACT(YEAR FROM age) * 12 + EXTRACT(MONTH FROM age) AS months_between
    FROM age(TIMESTAMP '2012-06-13 10:38:40', TIMESTAMP '2011-04-30 14:38:40') AS t(age);
    
    0 讨论(0)
提交回复
热议问题