Calculate age

EasyDatetime Programs · 6 of 20

Write a Python program to calculate a person’s age on a given date.

Advertisement
Input
born 1995-12-20, on 2026-11-02
Output
30

Approach

  1. Subtract years, then subtract 1 if the birthday has not come yet.

Solution

Python
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.

More datetime programs

← All 20 Datetime Programs

Leave a Comment