Python Program to Calculate Age from a Date of Birth
Beginner · Dates and times
This program works out a person's age in years from their date of birth. Subtracting the years is not enough on its own: someone born in December has not had this year's birthday yet in October, so the program also checks whether the birthday has come.
Program
Date of birth: 05 December 2008 Today: 18 October 2026 Age: 17 years
How it works
date(2008, 12, 5)makes a date object for 5 December 2008, written as year, month, day.- The first guess at the age is
today.year - birth_date.year, which is 18 here. - Tuples are compared item by item, so
(today.month, today.day) < (birth_date.month, birth_date.day)isTruewhen this year's birthday is still to come. - In that case one year is taken off, giving 17, because the 18th birthday is not until 5 December.
- The program uses a fixed "today" so its output never changes; use
date.today()from the comment to work from the real date.
Other ways to write it
Age in years, months and days
Age: 17 years, 10 months and 13 days
This works like subtraction with borrowing: when the days or the months come out negative, one month or one year is borrowed from the next column.
Days lived and the next birthday
Days lived: 6526 Next birthday: 05 December 2026 Days to go: 48
Subtracting two dates gives a timedelta, whose .days is the gap in days. replace(year=...) moves the birthday into this year; a 29 February birthday needs extra care, since most years have no such date.
Try it yourself
Change the date of birth to date(2008, 10, 18) to check that someone whose birthday is today gets the new age.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises