56

I think this should be simple but what I've seen are techniques that involve iterating over a dataframe date fields to determine the diff between two dates. And I'm having trouble with it. I'm familiar with MSSQL DATEDIFF so I thought Pandas datetime would have something similar. I perhaps it does but I'm missing it.

Is there a Pandonic way of determing the number of months as an integer between two dates (datetime) without the need to iterate? Keep in mind that there potentially are millions of rows so performance is a consideration.

The dates are datetime objects and the result would like this - new column being Month:

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

6 Answers 6

108

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)
11
  • 2
    just convert to integer with astype('int') bro Commented Mar 15, 2017 at 23:56
  • 4
    df['month'] = ((df.date2 - df.date1) / np.timedelta64(1, 'M')).astype(int) does the trick. Completes quickly. Thanks bro.
    – shavar
    Commented Mar 16, 2017 at 0:01
  • 2
    I concur with discort. The other solution is better as it takes care of rounding. The .asType method suggested here fails with NaT rows (which you may get if you had just calculated a 'Next Date' field where the last row is always a NaT)
    – Reddspark
    Commented Jan 21, 2018 at 20:55
  • 12
    Beware: this rounds to, e.g., 0 months between Feb 1 and March 1 -- is that what you really want? It gives slightly more or less than a whole number of months depending on the months in question. For instance, (pd.Timestamp('2018-03-01') - pd.Timestamp('2018-02-01')) / np.timedelta64(1, 'M') == 0.91993675. @piRSquared's solution, or .round() is probably better.
    – Doctor J
    Commented Sep 21, 2018 at 23:28
  • 3
    Assuming you are running Python 3, you could use the // operator to do integer division to get the integer df['nb_months'] = (df.date2 - df.date1) // np.timedelta64(1, 'M') Commented Mar 4, 2019 at 0:04
52

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

Since Pandas 0.24, this expression return an offset, which can be turned into an integer with delta.apply(lambda x: x.n)

4
  • 3
    I think this is the more correct answer, as rounding errors sure cause trouble.
    – Nils
    Commented Apr 7, 2019 at 13:26
  • 6
    to return Series of int, use following code; from operator import attrgetter (df.Date2.dt.to_period('M') - df.Date1.dt.to_period('M')).to_period('M')).apply(attrgetter('n')) as per this post
    – h2ku
    Commented Jan 8, 2020 at 5:00
  • 2
    Doesn't work for pandas version > 0.24.0. See this answer for updated code.
    – gherka
    Commented Feb 6, 2020 at 12:40
  • 1
    pandas v2+: delta = df.Date2.dt.to_period('M').astype(int) - df.Date1.dt.to_period('M').astype(int) gives you the number of months directly. Conversion of period to int gives number of months since 1970. Commented Apr 11 at 13:19
30
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
2
  • This one works as well. I get 10 and 1 months. With @Noobie solution I get 9 and 1. So this one is inclusive. Depending on my needs for any particular project both are super useful. Thanks.
    – shavar
    Commented Mar 16, 2017 at 0:18
  • 4
    or simply: df["Months"] = (df.Date2.dt.year - df.Date1.dt.year) * 12 + (df.Date2.dt.month - df.Date1.dt.month)
    – Nicolas
    Commented Oct 22, 2018 at 13:51
13

This should work:

df['Months'] = df['Date2'].dt.to_period('M').astype(int) - df['Date1'].dt.to_period('M').astype('int64')

df

# Out[11]: 
#        Date1      Date2  Months
# 0 2016-04-07 2017-02-01      10
# 1 2017-02-01 2017-03-05       1
2
  • 1
    Thank you, some of the other solutions don't work anymore Commented Jan 31, 2023 at 8:05
  • 1
    For future reference, I got an error when using astype(int) since it's no longer supported. Use astype('int64') instead. Commented Feb 16 at 7:46
8

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
0
4

There are two notions of difference in time, which are both correct in a certain sense. Let us compare the difference in months between July 31 and September 01:

import numpy as np
import pandas as pd

dtr = pd.date_range(start="2016-07-31", end="2016-09-01", freq="D")
delta1 = int((dtr[-1] - dtr[0])/np.timedelta64(1,'M'))
delta2 = (dtr[-1].to_period('M') - dtr[0].to_period('M')).n
print(delta1,delta2)

Using numpy's timedelta, delta1=1, which is correct given that there is only one month in between, but delta2=2, which is also correct given that September is still two months away in July. In most cases, both will give the same answer, but one might be more correct than the other given the context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.