i need a python code for calculating the age
- User
i need a python code for calculating the age
Assistant
Sure! Here's a simple Python code that calculates the age of a person based on their date of birth:
# Ask the user for their date of birth birth_date = input("Enter your date of birth (YYYY-MM-DD): ") # Parse the date of birth into a Python date object birth_date = datetime.strptime(birth_date, "%Y-%m-%d") # Calculate the age of the person age = datetime.now().year - birth_date.year # Print the age print("You are", age, "years old.")Here's how the code works:
- We ask the user to enter their date of birth in the format YYYY-MM-DD.
- We use the
strptime()method to parse the date of birth into a Python date object. - We calculate the age of the person by subtracting the year of their birth date from the current year.
- We print the age of the person.
Note that this code assumes that the current year is the year that the code is being run. If you want to calculate the age based on a different year, you can simply change the value of the variable to the desired year.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.