Count months between two timestamp on postgresql?

前端 未结 11 1144
一个人的身影
一个人的身影 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: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);
    

提交回复
热议问题