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.
datetime.datetime(year, month, day)
twice to create two datetimes
from two specific dates. datetime.month
attribute of one datetimes
from the other datetimes
to get the difference in months. datetime.year
attribute of one datetimes
from the other datetimes
and then, multiply the result by 12 to get the difference in months. Here is an example of how to get the total number of months between two specific dates.
# 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)
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!
Comments