In this article, we will discuss how to get the difference between two dates in months in python.

In python, the dateutil module provides a class relativedelta, which represents an interval of time. The relativedelta class has following attributes which tells about the duration,

  • Year
  • Month
  • Day
  • Hours
  • Minutes
  • Seconds
  • Microseconds

So, to calculate the difference between two dates in years, we can create a relativedelta object, that represents the interval between two given dates. Then we can fetch the Years and Month attributes of object (like relativedelta.months + relativedelta.years * 12). It will tell us the difference between two dates in Months. Let’s understand with some examples,

Python Example 1: Get difference between two dates in months

Suppose we have two dates in string format. We can convert them to datetime objects using datetime.strptime() function. Then we will get the interval between two dates as a relativedelta object. Then using the years and months property of relativedelta object, we will fetch the years in between the two dates. For example,

from datetime import datetime
from dateutil import relativedelta

date_1 = '2/7/2021'
date_2 = '24/3/2032'

start = datetime.strptime(date_1, "%d/%m/%Y")
end =   datetime.strptime(date_2, "%d/%m/%Y")

# Get the interval between two dates
diff = relativedelta.relativedelta(end, start)

diff_in_months = diff.months + diff.years * 12
print('Difference between dates in months:')
print(diff_in_months)

Output:

Difference between dates in months:
128

Python Example 2: Get difference between two dates in months

Instead of calculating the difference between two datetime objects using relativedelta. We can manually calculate the difference in months. For example,

from datetime import datetime

date_1 = '2/7/2021'
date_2 = '24/3/2032'

start = datetime.strptime(date_1, "%d/%m/%Y")
end =   datetime.strptime(date_2, "%d/%m/%Y")

diff = (end.year - start.year) * 12 + (end.month  - start.month )

print('Difference between dates in months:')
print(diff)

Output:

Difference between dates in months:
128

Because we are interested till months only, so it is a quicker solution as compared to previous one.

Python Example 3: Get difference between two dates in months

If you have some existing datetime objects instead of string then we can get the difference between those two datetime objects in months like this,

from datetime import datetime

start = datetime(2021, 7, 2)
end = datetime(2032, 11, 24)

diff = (end.year - start.year) * 12 + (end.month  - start.month )

print('Difference between dates in months:')
print(diff)

Output:

Difference between dates in months:
136

Summary:

We learned that, in python how to get the difference between two dates in months.