Home > Back-end >  Print current age given the date of birth
Print current age given the date of birth

Time:06-28

I have to make a code outside of a function where I print the current age given the input of the date of birth. So far I've got this:

from datetime import date, datetime
birth1 = input("Input your date of birth (dd/mm/yyyy):")

currentDate = date.today()
birth2 = datetime.strptime(birth1, "%d/%m/%Y").date()
age = currentDate - birth2

But I'm stuck here. How can I make it so the var "age" gets the current age from the person so I can later print it in something like this:

print(age, "years old")

CodePudding user response:

See below code -it should work for you

enter image description here

CodePudding user response:

age = currentDate.year - birth2.year
if currentDate.month < birth2.month or \
  (currentDate.month == birth2.month and currentDate.day < birth2.day):
  age -= 1
print(age, "years old")
  • Related