Home > Software design >  How to calculate age as years, months, and days?
How to calculate age as years, months, and days?

Time:10-20

I have two pairs of date data:

date_pair1 = [datetime.datetime(2021,3,1) , datetime.datetime(2020,2,1)]
date_pair2 = [datetime.datetime(2021,4,1) , datetime.datetime(2021,3,1)]

With Python:

delta1 = (date_pair1[0]-date_pair1[1]).days
delta2 = (date_pair2[0]-date_pair2[1]).days
year = 365
month = 30
age1 = f"{delta1//365} year {(delta1%365)//30} month {(delta1%365)%30} day"
age2 = f"{delta2//365} year {(delta2%365)//30} month {(delta2%365)%30} day"
print(age1,"-",age2)

Result:

1 year 0 month 29 day - 0 year 1 month 1 day

With Excel:

E5 cell:1.02.2020 F5 cell:1.03.2021

E6 cell:1.03.2021 F6 cell:1.04.2021

Using DATEDIF function:

=CONCAT(DATEDIF(E5,F5,"Y")," year ",DATEDIF(E5,F5,"YM")," month ",DATEDIF(E5,F5,"MD")," day")
=CONCAT(DATEDIF(E6,F6,"Y")," year ",DATEDIF(E6,F6,"YM")," month ",DATEDIF(E6,F6,"MD")," day")

1 year 1 month 0 day - 0 year 1 month 0 day

How can I get the results in Excel using python?

CodePudding user response:

Use relativedelta

date_pair1 = [datetime.datetime(2021,3,1) , datetime.datetime(2020,2,1)]
date_pair2 = [datetime.datetime(2021,4,1) , datetime.datetime(2021,3,1)]

from dateutil.relativedelta import relativedelta
delta1 = relativedelta(date_pair1[0],date_pair1[1])
delta2 = relativedelta(date_pair2[0],date_pair2[1])
year = 365
month = 30
age1 = f"{delta1.years} year {delta1.months} month {delta1.days} day"
age2 = f"{delta2.years} year {delta2.months} month {delta2.days} day"
print(age1,"-",age2)
  • Related