Count months between two timestamp on postgresql?

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

    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.

提交回复
热议问题