Python program: Age and days until a birthday
Work out an exact age and the days until the next birthday.
The code
from datetime import date def age_on(birth, today): years = today.year - birth.year if (today.month, today.day) < (birth.month, birth.day): years -= 1 # birthday not reached yet this year return years birth = date(1999, 3, 14) today = date(2026, 11, 17) print("age:", age_on(birth, today)) next_bday = birth.replace(year=today.year) if next_bday < today: next_bday = next_bday.replace(year=today.year + 1) print("days to next birthday:", (next_bday - today).days)
Output
age: 27 days to next birthday: 117
How it works
Comparing (month, day) tuples checks whether this year's birthday has passed. Subtracting dates gives a timedelta whose .days is the gap. (People born on 29 February need one more check.)
Python features used
Learn the ideas behind it in the free lesson Modules & the Standard Library.