Python: Calculate an age in year
Python Datetime: Exercise-39 with Solution
Write a Python program to calculate an age in years.
Sample Solution:
Python Code:
# Import the date class from datetime module
from datetime import date
# Define a function called calculate_age which calculates the age based on the date of birth
def calculate_age(dtob):
# Get the current date
today = date.today()
# Calculate the age by subtracting the birth year from the current year
# Adjust the age if the birth month and day are after today's month and day
return today.year - dtob.year - ((today.month, today.day) < (dtob.month, dtob.day))
# Print an empty line
print()
# Print the age calculated based on the date of birth October 12, 2006
print(calculate_age(date(2006,10,12)))
# Print the age calculated based on the date of birth January 12, 1989
print(calculate_age(date(1989,1,12)))
# Print an empty line
print()
Output:
10 28
Explanation:
In the exercise above,
- The code imports the "date" class from the "datetime" module.
- It defines a function named "calculate_age()" which calculates the age based on the provided date of birth (dtob).
- Inside the "calculate_age()" function:
- It gets the current date using "date.today()" function.
- It calculates age by subtracting the birth year from the current year.
- It adjusts the age if the birth month and day are after today's month and day.
- It calculates and prints the age based on the date of birth October 12, 2006, by calling the "calculate_age()" function.
- It calculates and prints the age based on the date of birth January 12, 1989, by calling the "calculate_age()" function.
Flowchart:
Python Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Python program to get last modified information of a file.
Next: Write a Python program to get the current date time information.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/date-time-exercise/python-date-time-exercise-39.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics