Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate years + months + days between 2 dates? [duplicate]

I have 2 person's birth information, I want to do some analysis on them. Like, the difference between their age, seconds, years+months+days. I tried this:

from datetime import date
a = date(1991, 07, 20)
b = date(1999, 06, 06)
print((a-b).days)
-2878

this gives me 2878 days, but i want to calculate years + months + days i tried to divide 2878/365, but i want the exact calculations How can i approach this?

Expected Output:

7 years x months x days
like image 707
Tarun K Avatar asked Oct 28 '25 03:10

Tarun K


1 Answers

Use datetime and dateutil:

from datetime import datetime
from dateutil import relativedelta

date1 = datetime(1991, 7, 20)
date2 = datetime(1999, 6, 6)

diff = relativedelta.relativedelta(date2, date1)

years = diff.years
months = diff.months
days = diff.days

print('{} years {} months {} days'.format(years, months, days))
# 7 years 10 months 17 days
like image 74
Austin Avatar answered Oct 29 '25 17:10

Austin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!