Count months between two timestamp on postgresql?

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

提交回复
热议问题