Calculate age from date of birth in Python

I’ll show you how to calculate your age in years, months, and days using Python. The script will ask for the day, month, and year of your birth, and it will output your exact age. With a few simple adjustments, this script can also be used for other datetime calculations.

days months years of yours

Age calculations

Here’s a Python script that calculates age based on a given birth date:

import datetime
birth_day = int(input("Day of birth: "))
birth_month = int(input("Month of birth: "))
birth_year = int(input("Year of birth: "))
day = int(datetime.date.today().day)
month = int(datetime.date.today().month)
year = int(datetime.date.today().year)
if birth_year > year:
   age = year - birth_year
else:
   age = (year - birth_year) - 1
b = abs(month - birth_month)
c = abs(day - birth_day)
print("Your age is:", age, "years", b, "months", c, "days")

The script first imports the Python datetime module. This module provides functions for working with dates and times.

See also  How to calculate absolute value using Numpy

The next three lines of code ask the user for their birthday date. The day, month, and year are then stored in the birth_day, birth_month, and birth_year variables.

The next three lines of code get the current date. The day, month, and year are then stored in the day, month, and year variables.

The next line of code checks if the birth year is greater than the current year. If it is, then the user is younger than one year old and the age is set to zero. Otherwise, the age is calculated as the difference between the current year and the birth year, minus one.

See also  Building Microservices with Python and Nameko

The next two lines of code calculate the number of months and days between the user’s birthday and the current date.

The final line of code prints the user’s age, number of months, and number of days.

Ideas to improve the script

Here are some ideas for how you can modify the script:

Calculate the age of someone else by asking for their birthday information.
Calculate the age of someone who was born on a specific date, such as your favorite celebrity or historical figure.
Calculate the number of days, weeks, or months until your next birthday.
Calculate the number of years, months, or days since a specific event, such as your wedding day or the day you graduated from college.

See also  How to convert cm to inch?

You learned how to calculate your age in years, months, and days using Python. The script is a simple way to calculate your age, but it can be modified to calculate the age of other people or to perform other datetime calculations.