Home » Get difference between two dates in months using python

Get difference between two dates in months using python

Oracle Java Certification
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Programmer II [1Z0-816] Practice Tests
Spring Framework Basics Video Course
1 Year Subscription
Java SE 11 Developer (Upgrade) [1Z0-817]

In this article we will look at two ways of showing the difference between two dates in months

Table of Contents

Example 1

from datetime import datetime

startdate = datetime(2018, 6, 2)
enddate = datetime(2022, 4, 9)
# Calculate the Total Number of months between the two dates
diff = (enddate.year - startdate.year) * 12 + (enddate.month  - startdate.month )
print('Difference between dates in months: ')
print(diff)

Lets try this example out

>>> %Run diffdatemonths1.py
Difference between dates in months: 
46

Example 2

In thi sexample we will get the interval between two dates as a relativedelta object

from datetime import datetime
from dateutil import relativedelta

startdate = '2/6/2018'
enddate = '9/4/2022'

start = datetime.strptime(startdate, "%d/%m/%Y")
end =   datetime.strptime(enddate, "%d/%m/%Y")

# Get the interval between two dates
diffdate = relativedelta.relativedelta(end, start)
diffinmonths = diffdate.months + diffdate.years * 12

print('Difference between dates in months: ')
print(diffinmonths)

Lets see a test run

>>> %Run diffdatemonths2.py
Difference between dates in months: 
46

Link

This is in our github repository

https://github.com/programmershelp/maxpython/tree/main/code%20example/Date%20examples

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More