Sure, I can help you with that. Here's a Python program that calculates the age of a person based on their birthdate in the format of year-month-day:
import datetime
def calculate_age(birthdate):
# Get the current date
today = datetime.date.today()
# Calculate the difference between the current date and the birthdate
age = today.year - birthdate.year
# If the current month is less than the birth month, subtract 1 from the age
if today.month < birthdate.month:
age -= 1
# If the current day is less than the birth day, subtract 1 from the age
if today.day < birthdate.day:
age -= 1
return age
# Test the function with a sample birthdate
birthdate = datetime.date(1995, 1, 1)
age = calculate_age(birthdate)
print(f"You are {age} years old.")
Let me explain the program step by step:
- The first line imports the
datetime module, which provides functions for working with dates and times in Python.
- The
calculate_age function takes a birthdate parameter, which is a datetime.date object representing the person's birthdate.
- The function starts by getting the current date using
datetime.date.today().
- Next, it calculates the difference between the current date and the birthdate using
today.year - birthdate.year. This gives us the number of years the person has lived.
- If the current month is less than the birth month, we subtract 1 from the age, because the person has not yet had their birthday in the current year. We do the same thing if the current day is less than the birth day.
- Finally, we return the age as a string in the format of "You are [age] years old."
- In the last line of the program, we call the
calculate_age function with a sample birthdate of January 1, 1995, and print the result.
That's it! This program should give you the correct