QA Graphic

Python Date

Calculate Date Duration in Python

Python Relativedelta

Recently, I created a function to calculate the number of days from today. This simple function accepts a date object and returns the number of Years, Months, and Days between now and that event.

I used the Relativedelta object from the Date library. It's an easy way to do the converting with a few lines of code. Since Relativedelta is part of Python3, it will scale very nicely.

The Relativedelta type has a lot of the same attribute that is found in PHPs Date library.

In the example below I was able to convert a 10 line PHP function to 3 lines of code. I am sure there's even more refactoring that can be done.

#!/usr/bin/env /usr/bin/python3
from datetime import date
from datetime import datetime
from dateutil import relativedelta
NOW = datetime.now()
def datecal(someday):
	caldate = relativedelta.relativedelta(NOW,someday );
	return  f"{caldate.years} years, {caldate.months} months. {caldate.days} days";
day1 = datecal(date(1775,7,4))
	
print(day1)	
#  246 years, 5 months. 3 days