Calculate Age from Date of Birth in Python: Simple Guide
To calculate age from date of birth in Python, use the
datetime module to get today's date and subtract the birth date. Then adjust the result to account for whether the birthday has occurred this year.Syntax
Use the datetime module to work with dates. The main parts are:
datetime.date.today(): gets today's date.datetime.date(year, month, day): creates a date object for the birth date.- Subtract birth year from current year, then adjust if birthday hasn't happened yet this year.
python
from datetime import date def calculate_age(birthdate): today = date.today() age = today.year - birthdate.year if (today.month, today.day) < (birthdate.month, birthdate.day): age -= 1 return age
Example
This example shows how to calculate the age of a person born on July 20, 1990.
python
from datetime import date def calculate_age(birthdate): today = date.today() age = today.year - birthdate.year if (today.month, today.day) < (birthdate.month, birthdate.day): age -= 1 return age birth_date = date(1990, 7, 20) age = calculate_age(birth_date) print(f"Age is: {age}")
Output
Age is: 33
Common Pitfalls
Common mistakes include:
- Not adjusting the age if the birthday hasn't happened yet this year, which can make the age one year too high.
- Using
datetime.datetimeinstead ofdatetime.datewithout handling time parts. - Forgetting to import the
datetimemodule.
python
from datetime import date # Wrong way: does not check if birthday passed this year def wrong_calculate_age(birthdate): today = date.today() return today.year - birthdate.year # Right way: adjusts if birthday not passed def right_calculate_age(birthdate): today = date.today() age = today.year - birthdate.year if (today.month, today.day) < (birthdate.month, birthdate.day): age -= 1 return age
Quick Reference
Remember these tips when calculating age:
- Use
datetime.datefor dates without time. - Subtract birth year from current year.
- Check if birthday has occurred this year to adjust age.
- Use tuple comparison for month and day to simplify logic.
Key Takeaways
Use the datetime module's date class to handle dates simply.
Calculate age by subtracting birth year from current year and adjust if birthday hasn't occurred yet this year.
Always compare month and day as a tuple to decide if you should subtract one from age.
Avoid using datetime.datetime if you only need date parts to keep code clean.
Test your function with birthdays before and after today's date to ensure accuracy.