Python Practice › Datetime Programs › Program 6
Calculate age
Write a Python program to calculate a person’s age on a given date.
Input
born 1995-12-20, on 2026-11-02
Output
30
Approach
- Subtract years, then subtract 1 if the birthday has not come yet.
Solution
from datetime import date def age(birth, on): years = on.year - birth.year if (on.month, on.day) < (birth.month, birth.day): years -= 1 return years print(age(date(1995, 12, 20), date(2026, 11, 2)))Output
30
Learn the concept
New to this topic? Read the lesson, then come back.