6

I am attempting to create some 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?

7
  • offtopic: never start the name of a variable with caps, use date_of_birth and todays_date instead. Commented Mar 16, 2017 at 19:42
  • 1
    How is it not running as you would hope? Please explain. Commented Mar 16, 2017 at 19:43
  • It does not run at all, it blows up and says 'str' has no attribute to year Commented Mar 16, 2017 at 19:44
  • 1
    When you post a question you should give the error message. Something like "3 14 1995" is just a string. Python won't interpret it as a date unless you tell it to. Commented Mar 16, 2017 at 19:47
  • 1
    Input is texte string not a date object. You need co nvert it with with born = datetime.strptime(Date_of_birth, "%m %d %Y") same for Todays_date if it is input value Commented Mar 16, 2017 at 19:48

4 Answers 4

14

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

Sign up to request clarification or add additional context in comments.

2 Comments

mm dd yyyy is pretty sensible and common in the US
# Given values current_age = 39 current_size = 9.47 # Calculate the rate of change (m) rate_of_change = current_size / current_age print(rate_of_change)
2

This should work :)

from datetime import date

def ask_for_date(name):
    data = raw_input('Enter ' + name + ' (yyyy mm dd): ').split(' ')
    try:
        return date(int(data[0]), int(data[1]), int(data[2]))
    except Exception as e:
        print(e)
        print('Invalid input. Follow the given format')
        ask_for_date(name)


def calculate_age():
    born = ask_for_date('your date of birth')
    today = date.today()
    extra_year = 1 if ((today.month, today.day) < (born.month, born.day)) else 0
    return today.year - born.year - extra_year

print(calculate_age())

Comments

1

You can also use date time library in this manner. This calculates the age in years and removes the logical error that returns wrong age due to the month and day properties

Like a person born on 31 July 1999 is a 17 year old till 30 July 2017

So here's the code :

import datetime

#asking the user to input their birthdate
birthDate = input("Enter your birth date (dd/mm/yyyy)\n>>> ")
birthDate = datetime.datetime.strptime(birthDate, "%d/%m/%Y").date()
print("Your birthday is on "+ birthDate.strftime("%d") + " of " + birthDate.strftime("%B, %Y"))

currentDate = datetime.datetime.today().date()

#some calculations here 
age = currentDate.year - birthDate.year
monthVeri = currentDate.month - birthDate.month
dateVeri = currentDate.day - birthDate.day

#Type conversion here
age = int(age)
monthVeri = int(monthVeri)
dateVeri = int(dateVeri)

# some decisions
if monthVeri < 0 :
    age = age-1
elif dateVeri < 0 and monthVeri == 0:
    age = age-1


#lets print the age now
print("Your age is {0:d}".format(age))

Comments

0
 from datetime import datetime, date
def calculateAge(birthDate): 
    today = date.today() 
    age = today.year - birthDate.year - ((today.month, today.day) < (birthDate.month, birthDate.day)) 
    return age 
d=input()
year=d[0:4]
month=d[5:7]
day=d[8:]
if int(month)<=0 or int(month)>12:
    print("WRONG")
elif int(day)<=0 or int(day)>31:
    print("WRONG")
elif int(month)==2 and int(day)>29:
    print("WRONG")
elif int(month) == 4 or int(month) == 6 or int(month) == 9 or int(month) ==11 and int(day) > 30:
    print("WRONG")
else:       
    print(calculateAge(date(int(year),int(month),int(day))))

This code will work correctly for every date.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.