0

I am attempting to calculate the age of a person from their date of birth entered, using python.

I have already tried this and this but have not found the answer.

I have done the following :

Import datetime, date

from datetime import datetime, date

Create the following notation:

print ('Enter your date of birth here (dd mm yyyy): ')
date_of_birth = datetime.strptime(str(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)

However when I enter the date in this format 9121991 :

I get this value error.

Incidentally when I enter it in this 09121991 format, I recieved this error

enter image description here

How can I correct this?

Waltham WECAN
  • 481
  • 4
  • 11
  • 26

1 Answers1

1

Since your format has spaces in it, it is unable to recognize your string.

That works:

from datetime import datetime, date

date_of_birth = datetime.strptime("09121991", '%d%m%Y')

Note that you cannot use input to enter 09121991 because in Python 2:

  • input evaluates the expression
  • 09121991 is seen as an octal number, but invalid because it contains 9

So the alternative is using raw_input(). That'll work.

BTW: If you need to pad with zeroes use raw_input().zfill(8). No need to add the leading zeroes using that trick.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219