Find the no of Months between Two Dates in Python

In this tutorial, we will learn how to find the no of months between two dates in Python. We will learn mainly two things-

  • Algorithm for finding no. of months between two dates.
  • Python Program for finding a number of months between two dates.

In Python, it is a very easy task as there is an inbuilt module/package ‘datetime’ to handle date-time operations. So, let’s see.

Find the number of months between two dates in Python

Algorithm

  • Import the ‘datetime’ module.
  • Create two datetime objects for the starting date and ending date by calling
datetime.datetime(year, month, date)

[the first datetime is the package name and the second one is the class name].

N.B: The range for the parameters must be like the following-

1<=year<=9999

1<=month<=12

1<=day<=max no of days in that month and year

  • Subtract the datetime.year attribute of one datetime from the other and multiply the result by 12 to get the difference in months.
  • Similarly, subtract the datetime.month attribute of one datetime from the other to get the difference in months.
  • Add these two to get the actual no of months between the two dates.

Python Program

import datetime

st_date = datetime.datetime(2018,9,16)
end_date = datetime.datetime(2020,3,24)
months = (end_date.year - st_date.year) * 12 + (end_date.month - st_date.month)
print('The difference in months is: ',months)

Output:

The difference in months is: 18

The above code is just the implementation of the above algorithm. So, this is all about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *