Find the no of Months between Two Dates in Python

Hello friends, in this tutorial, I will tell you how to count the number of months between two dates in Python.

Find the number of months between two dates in Python

In the tutorial, I will cover two methods of performing this task.

  • Input is provided in string format
  • Input is given as datetime object

First Method

I have used Python’s built-in module datetime for calculation. After importing the datetime module from the datetime package, I have defined two dates as strings and stored them in variables, d1 and d2. Now I have two date strings but in order to perform operations I need to convert them to a datetime object. strptime() function converts a date string to a datetime object. It takes two attributes as an argument, the first being the string and the other being the format of the string. Now that I have obtained two objects I can subtract d1 from d2. This provides me results in the form of days, seconds, and microseconds. To obtain the number of days, I have used the days attribute.

Code :

from datetime import datetime

d1 = '2018-09-16'
d2 = '2020-03-24'

d1 = datetime.strptime(d1, "%Y-%m-%d")
d2 = datetime.strptime(d2, "%Y-%m-%d")

days = (d2 - d1)
months = (days.days) // 30
print(months)

Output : 

18

After calculating the number of days, I divided it by 30. As I only need the number of months I have performed integer division, which returns me only the number of months.

Finding number of days along with months :

If you wish to calculate both the number of days and months, you can find the remainder. This provides you with the number of days.

Code : 

day = days.days % 30
print("Months :", months, "and days :", day)

Output :

Months : 18 and days : 15

Alternate Method

Import the datetime package to your code.  I have defined two datetime objects, st_date and end_date.  I have obtained the year and month of the date using the year and month attribute respectively. Here I have used a simple expression to find the number of months. The difference between the end_date.year and st_date.year is multiplied by 12 to obtain the number of months in the following years. Now add the remaining months to the expression by finding the difference between the end_date.month and st_date.month.

Code :

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

Now you can calculate the number of months between two dates.

Leave a Reply

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