# of Months between two dates

MRAB python at mrabarnett.plus.com
Sun Aug 8 20:16:51 CEST 2010

Greg Lindstrom wrote:
> I work for a company that processes claims for the health care industry 
> (Novasys Health, recently purchased by Centene Corp).  My current 
> assignment has me writing a routine to compute insurance premiums.  One 
> of the requirements is to determine how many months a policy has been in 
> effect.  The datetime module will give me the number of days but, with 
> months having different lengths, that does not do me much good.  I've 
> looked in the calendar library but didn't see anything there, either.
> I've written a function to return the months between date1 and date2 but 
> I'd like to know if anyone is aware of anything in the standard library 
> to do the same?  For bonus points, does anyone know if postgres can do 
> the same (we use a lot of date/time funcitons in postgres, already, but 
> didn't see this problem addressed).
A simple expression is:

     diff = (current_year - start_year) * 12 + (current_month - start_month)

According to this, if a policy started on 31 July 2010, then on 1 August
2010 it has been in effect for 1 month. Is this reasonable? It depends!

It's probably better to write the function yourself according to what
makes sense in your use-case, and document its behaviour clearly.

More information about the Python-list mailing list