How to Calculate Age in Python (datetime and Birthday Logic Examples)
Learn how to calculate age from date of birth in Python using datetime, with a simple birthday check for completed years.
How to Calculate Age in Python (datetime and Birthday Logic Examples)
In Python, age usually means the number of completed years. The reliable pattern is simple: subtract the birth year, then reduce by one if the birthday has not happened yet in the reference year.
Fast option: use an online age calculator
If you want a quick check, or you need an exact result in years, months, and days, verify the dates in a calculator first and then mirror the same rule in code.
Open the age calculator and enter the date of birth plus the reference date.
Python example with datetime.date
This helper returns completed years as of a given date.
from datetime import date
def age_years(dob: date, as_of: date | None = None) -> int:
as_of = as_of or date.today()
years = as_of.year - dob.year
had_birthday = (as_of.month, as_of.day) >= (dob.month, dob.day)
return years if had_birthday else years - 1
print(age_years(date(1998, 10, 12)))
Parsing from an ISO date string
If the input already looks like 1998-10-12, parse it before passing it to the helper.
from datetime import date
def age_from_iso(dob_str: str, as_of: date | None = None) -> int:
dob = date.fromisoformat(dob_str)
return age_years(dob, as_of)
print(age_from_iso('1998-10-12'))
FAQ
Why not divide the day difference by 365.25?
That can work as a rough estimate, but real age should follow birthdays. A direct birthday check avoids the usual off-by-one problems.
How do I calculate exact age in years, months, and days?
That is a separate problem because month lengths vary. It helps to validate your result with a dedicated calculator before using it in app logic.