top of page
realcode4you

Python Program to Calculate User’s Age Using Date of Birth in the Format mm/dd/yyyy

Instructions

Write a program that asks the user to input his/her date of birth in the format mm/dd/yyyy. (Note that this exercise uses the American format, not the European one so 03/25/2022 would be 25th March.)


If the input is not in the correct format or the date is invalid the program should output an appropriate error message. If the input is a valid date the program should calculate and output the user’s age. (You will need to check whether the user has had a birthday this year e.g. someone born in January 2000 will be 22 on 25th March 2022, but someone born in April will still be 21.) The program should additionally output the date in European format (e.g. 25/03/2022 for 25th March).


To calculate the age you will need to obtain today’s date; to do this you need to use the

line from datetime import date and then use date.today() to obtain a dateobject containing today’s date. Yo can access the day, month and year of a date dusing d.day, d.monthand d.year(these are all integer values).


Implementation

#%% Import date and datetime
from datetime import datetime
from datetime import date

#%% Function to carry out age calculation

def calculate_age(birth_date: datetime) -> int:
    '''
    Calculate the age from the input birth date.

    Parameters
    ----------
    birth_date : datetime
        The birth date to calculate the age from.

    Returns
    -------
    int
        The age calculated from the birth_date parameter.

    '''

    # get today's date
    today: date = date.today()
    
    # calculate the year difference between today and the date of birth
    difference: int = today.year - birth_date.year
    
    # find out if today preceeds the date of birth this year
    # this helps us know whether to subtract 1 year from the difference
    # if today preceeds the birthdate, we need to subtract one
    # otherwise, we subtract nothing
    
    # The tuples used for the comparison have to be ordered in the form
    # (month. day), so that when tuple comparison is carried out, months
    # will be compared first. If they are equal, then days will be compared
    today_preceeds_DOB: int = int((today.month, today.day) < (birth_date.month, birth_date.day))
    
    # calculate the age
    age: int = difference - today_preceeds_DOB
    
    # return calculated age
    return age


#%% The main program

try:
    # get the birthdate input from user in American format (mm/dd/yyyy)
    birth_date_str: str = input("Enter your birth date (mm/dd/yyyy): ")
    
    # parse the user input to make sure it is in the format mm/dd/yyyy
    birth_date: datetime = datetime.strptime(birth_date_str, '%m/%d/%Y')

except ValueError as err:
    # display a nice error message
    if str(err) == "day is out of range for month":
        print(err)
        
    else:
        print(f"User input '{birth_date_str}' is not in the format mm/dd/yyyy")
        
    
else:
    # calculate the user's age
    age: int = calculate_age(birth_date)
    
    # output the user's date of birth and age
    
    # output the date of birth in European format dd/mm/yyyy
    print(f"Your date of birth is {birth_date:%d/%m/%Y}")
    
    # print out the age
    print(f"You are {age} years old.")

Output:


Comments


bottom of page