Age from birthdate in python
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
To calculate age from a birthdate in Python, the usual approach is to subtract the birth year from the current year and then adjust if the birthday has not happened yet this year. That sounds simple, but doing it correctly means comparing month and day rather than dividing a raw day count by 365.
The standard datetime.date solution
This works because age is really "how many birthdays have passed", not "how many days divided by a rough year length".
Why subtracting days is not enough
A tempting but incorrect approach is:
That fails around leap years and birthdays because calendar years are not all the same length. Age is a calendar concept, not a fixed number of days.
A concrete example
Even though the year numbers differ by 25, the birthday has not happened yet in 2025, so the correct age is 24.
Handling leap-day birthdays
Leap-day birthdays require a policy decision. If someone was born on February 29, how should age be handled in non-leap years? Many systems simply keep the same month and day comparison logic and rely on the calendar meaning of the date.
If your domain needs a special rule, such as treating February 28 or March 1 as the birthday in non-leap years, implement that rule explicitly rather than assuming there is one universally correct answer.
Parsing from strings
If the birthdate arrives as a string, parse it first:
Separating parsing from age calculation keeps the logic easier to test.
Using dateutil.relativedelta
If you already use python-dateutil, relativedelta can express calendar differences directly.
This is convenient, but it adds a dependency. For many scripts, the standard-library function is perfectly adequate.
Use date, not full timestamps, when possible
Age is usually a calendar concept, not a time-of-day concept. Converting to date objects early avoids confusing edge cases where time zones or hours and minutes make the subtraction logic harder than it needs to be.
Validate impossible inputs
A future birthdate should usually be rejected:
This makes the function safer in forms, APIs, and data-cleaning pipelines.
Common Pitfalls
- Dividing day differences by
365and calling that age. - Forgetting to adjust when the birthday has not occurred yet this year.
- Ignoring future birthdates and returning negative ages.
- Mixing
datetimeanddateobjects without normalizing them. - Assuming leap-day birthdays need no special business-rule discussion.
Summary
- The correct age calculation compares year, month, and day, not just day counts.
- Subtract the years, then reduce by one if the birthday has not happened yet.
- Parse string input into a
datebefore calculating age. - Reject future birthdates explicitly when appropriate.
- Use
relativedeltaif you want a calendar-aware helper frompython-dateutil.

