Calculating age in python

A. Gunter picture A. Gunter · Mar 16, 2017 · Viewed 38.6k times · Source

I am attempting to create a code where the user is asked for their date of birth and today's date in order to determine their age. What I have written so far is:

print("Your date of birth (mm dd yyyy)")
Date_of_birth = input("--->")

print("Today's date: (mm dd yyyy)")
Todays_date = input("--->")


from datetime import date
def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

age = calculate_age(Date_of_birth)

However it is not running like I would hope. Could someone explain to me what I am doing wrong?

Answer

Attie picture Attie · Mar 16, 2017

So close!

You need to convert the string into a datetime object before you can do calculations on it - see datetime.datetime.strptime().

For your date input, you need to do:

datetime.strptime(input_text, "%d %m %Y")
#!/usr/bin/env python3

from datetime import datetime, date

print("Your date of birth (dd mm yyyy)")
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

age = calculate_age(date_of_birth)

print(age)

PS: I urge you to use a sensible order of input - dd mm yyyy or the ISO standard yyyy mm dd