Pandas - Number of Months Between Two Dates Pandas - Number of Months Between Two Dates pandas pandas

Pandas - Number of Months Between Two Dates


Here is a very simple answer my friend:

df['nb_months'] = ((df.date2 - df.date1)/np.timedelta64(1, 'M'))

and now:

df['nb_months'] = df['nb_months'].astype(int)


df.assign(    Months=    (df.Date2.dt.year - df.Date1.dt.year) * 12 +    (df.Date2.dt.month - df.Date1.dt.month))       Date1      Date2  Months0 2016-04-07 2017-02-01      101 2017-02-01 2017-03-05       1


An alternative, possibly more elegant solution isdf.Date2.dt.to_period('M') - df.Date1.dt.to_period('M'), which avoids rounding errors.