How to Calculate Age in Python (datetime and dateutil Examples)
Learn how to calculate age from date of birth in Python. Includes years completed, age as of a specific date, and common pitfalls like leap years and time zones.
How to Calculate Age in Python (datetime and dateutil Examples)
If you need to calculate age in Python from a date of birth, the main thing to get right is the definition of age: most apps need years completed (full birthdays), not just the difference between years.
1) Years completed (the safe definition)
This returns the number of full years since the date of birth (DOB). It subtracts 1 if the birthday has not happened yet in the current year.
from datetime import date
def age_years(dob: date, as_of: date | None = None) -> int:
if as_of is None:
as_of = date.today()
years = as_of.year - dob.year
before_birthday = (as_of.month, as_of.day) < (dob.month, dob.day)
return years - 1 if before_birthday else years
print(age_years(date(2000, 10, 5), date(2026, 2, 26)))
2) Age as of a specific date (not just today)
Many use cases need an "as of" date: insurance pricing, eligibility checks, school cutoffs, reports. The function above already supports it via as_of.
3) Exact style output (years and months)
If you want output like "25 years 4 months", use dateutil.relativedelta (it handles month lengths correctly).
from datetime import date
from dateutil.relativedelta import relativedelta
def age_ym(dob: date, as_of: date | None = None):
if as_of is None:
as_of = date.today()
rd = relativedelta(as_of, dob)
return rd.years, rd.months
print(age_ym(date(2000, 10, 5), date(2026, 2, 26)))
4) Common pitfalls (and how to avoid them)
- Leap day birthdays: decide how you want to treat Feb 29 in non leap years. Many systems use Feb 28 or Mar 1. Library behavior matters, so test it.
- Datetimes and time zones: for DOB, prefer
dateoverdatetime. If you must use datetimes, normalize to the same time zone first. - Future DOB or missing values: validate inputs to avoid negative ages or crashes.
Quick check (no code)
If you just need one result fast, use the online calculator: Calculate Age Online.
Related guides
- How to Calculate Age (complete guide)
- How to Calculate Age in Excel
- How to Calculate Age in JavaScript
FAQ
Why is (today.year - dob.year) wrong sometimes?
Because it ignores whether the birthday has already happened this year. You must subtract 1 before the birthday.
Should I use datetime or date for date of birth?
Use date when possible. DOB is a calendar day, and time zones can shift datetimes across days.