Python - Find age from string date
-
To find completed age in years, we need to check year, month and days difference. Following checks are to be done.
If birth month greater than current month, age birth year - current year.
If birth month less than current month, age is (birth year - current year) -1.
If birth month equals current month and birth day greater than or equal to current day, age is birth year - current year.
If birth month equals current month and birth day less than current day age is (birth year - current year) -1.Refer python sample below.
Copiedfrom datetime import datetime, date currentdate = date.today() bdate = datetime(2001, 3, 10) age = 0 if(currentdate.month > bdate.month): age = currentdate.year - bdate.year elif(currentdate.month < bdate.month): age = (currentdate.year - bdate.year) - 1 else: if(currentdate.day >= bdate.day): age = currentdate.year - bdate.year else: age = (currentdate.year - bdate.year) - 1 print("Age : " + str(age))
Age : 20 -
If the birth date is in string format, convert to datetime object before finding the age, as in sample below.
For more samples on string to date conversion refer Convert String to Datetime - All FormatsCopiedfrom datetime import datetime, date currentdate = date.today() birthdate = "04-15-02" bdate = datetime.strptime(birthdate, '%m-%d-%y') age = 0 if(currentdate.month > bdate.month): age = currentdate.year - bdate.year elif(currentdate.month < bdate.month): age = (currentdate.year - bdate.year) - 1 else: if(currentdate.day >= bdate.day): age = currentdate.year - bdate.year else: age = (currentdate.year - bdate.year) - 1 print("Age : " + str(age))
Age : 19