;

How to Get the Number of Months Between Two Dates in Python


Tutorialsrack 11/02/2021 Python

In this article, you will learn how to get the total number of months between two dates in python. There are various ways to achieve this and we are doing this in a simple way.

  • Here, we call datetime.datetime(year, month, day) twice to create two datetimes from two specific dates. 
  • After that, we Subtract the datetime.month attribute of one datetimes from the other datetimes to get the difference in months. 
  • Similarly, we subtract the datetime.year attribute of one datetimes from the other datetimes and then, multiply the result by 12 to get the difference in months. 
  • Add these two values to get the total number of months between the two specific dates.

Here is an example of how to get the total number of months between two specific dates.

Code - To Get the Number of Months Between Two Dates in Python
# How to Get the Number of Months Between Two Dates in Python

# Import Module
import datetime

# Create Two New Dates
start_date = datetime.datetime(2009, 1, 1)
end_date = datetime.datetime(2010,1,1)

# Calculate the Total Number of months between two dates
num_months = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)


print("Total No. of Months b/w Two Dates: ",num_months)
Output

Total No. of Months b/w Two Dates:  12

I hope this article will help you to understand how to get the total number of months between two dates in python.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags