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
- 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<=day<=max no of days in that month and year
- Subtract the
datetime.yearattribute of one datetime from the other and multiply the result by 12 to get the difference in months.
- Similarly, subtract the
- Add these two to get the actual no of months between the two dates.
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)
The difference in months is: 18
The above code is just the implementation of the above algorithm. So, this is all about this article.