809
In this article we will look at two ways of showing the difference between two dates in months
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