Count months between two timestamp on postgresql?

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

    SELECT floor(extract(days from TIMESTAMP '2012-06-13 10:38:40' - TIMESTAMP
    '2011-04-30 14:38:40')/30.43)::integer as months;
    

    Gives an approximate value but avoids duplication of timestamps. This uses hint from tobixen's answer to divide by 30.43 in place of 30 to be less incorrect for long timespans while computing months.

提交回复
热议问题