Bijan
Bijan

Reputation: 8680

Python Find # of Months Between 2 Dates

I am trying to find the # of months between 2 dates. Some solutions are off by 1 month and others are off by several months. I found This solution on SO but the solutions are either too complicated or incorrect.

For example, given the starting date of 04/30/12 and ending date of 03/31/16,

def diff_month(d1, d2):
    return (d1.year - d2.year)*12 + d1.month - d2.month

returns 47 months, not 48

and

dates = [dt for dt in rrule(MONTHLY, dtstart=strt_dt, until=end_dt)]

returns 44 (Reason being that February does not have a day # 30 so it does not see it as a valid date)

I can of course fix that by doing

dates = [dt for dt in rrule(MONTHLY, dtstart=strt_dt.replace(day=2), until=end_dt.replace(day=1))]

But this does not seem like a proper solution (I mean the answer is right but the method sucks).

Is there a proper way of calculating the # of months so that given my example dates, it would return 48?

Upvotes: 2

Views: 243

Answers (1)

Alexander
Alexander

Reputation: 109736

I realize this post doesn't have a Pandas tag, but if you are willing to use it you can simply do the following which takes the difference between two monthly periods:

import pandas as pd

>>> pd.Period('2016-3-31', 'M') - pd.Period('2012-4-30', 'M')
47

Upvotes: 4

Related Questions