Python Program To Calculate Age Of A Person
Chapter:
Python
Last Updated:
22-09-2023 04:54:25 UTC
Program:
/* ............... START ............... */
from datetime import datetime
def calculate_age(birthdate):
# Get the current date
current_date = datetime.now()
# Calculate the age by subtracting the birthdate from the current date
age = current_date.year - birthdate.year - ((current_date.month,
current_date.day) < (birthdate.month, birthdate.day))
return age
# Input the birthdate in the format YYYY-MM-DD
birthdate_str = input("Enter your birthdate (YYYY-MM-DD): ")
try:
# Convert the input string to a datetime object
birthdate = datetime.strptime(birthdate_str, "%Y-%m-%d")
# Calculate and print the age
age = calculate_age(birthdate)
print(f"Your age is {age} years.")
except ValueError:
print("Invalid date format. Please enter the date in YYYY-MM-DD format.")
/* ............... END ............... */
Output
Enter your birthdate (YYYY-MM-DD): 1990-05-15
Your age is 33 years.
In this example, the user entered the birthdate "1990-05-15," and the program
calculated the age as 33 years based on the current date.
Notes:
-
Here's how this program works:
- It takes user input for their birthdate in the format "YYYY-MM-DD."
- Then It converts the input string to a datetime object using strptime.
- In next step it calculates the age using the difference between the current date and the birthdate.
- Finally it prints the calculated age.
- Make sure to input the birthdate in the specified format (e.g., "1990-05-15"). The program will handle invalid date formats and raise a ValueError in such cases.