Pandas - Number of Months Between Two Dates

df.assign(
    Months=
    (df.Date2.dt.year - df.Date1.dt.year) * 12 +
    (df.Date2.dt.month - df.Date1.dt.month)
)

       Date1      Date2  Months
0 2016-04-07 2017-02-01      10
1 2017-02-01 2017-03-05       1

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)

Just a small addition to @pberkes answer. In case you want the answer as integer values and NOT as pandas._libs.tslibs.offsets.MonthEnd, just append .n to the above code.

(pd.to_datetime('today').to_period('M') - pd.to_datetime('2020-01-01').to_period('M')).n
# [Out]:
# 7

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

Tags:

Pandas

Date

Diff