In this post, we will learn how to calculate age from date of birth in Python with detailed explanations and examples. You can consider this Python program as your mini-project.

In this program, we will show your age with months and days. This is one of your coolest tools to calculate age from date of birth but before we jump into the programming part few programming concepts you have to know, which are:

  1. datetime module
  2. How to take input from the user
  3. if-else statements &
  4. Python Functions

Source Code

from datetime import date

def calculate_age(birth_date, current_date):
    # Calculation
    years = current_date.year - birth_date.year
    months = current_date.month - birth_date.month
    days = current_date.day - birth_date.day

    # Adjust for negative differences
    if days < 0:
        months -= 1
        days += get_days_in_month(birth_date.month, birth_date.year)
    if months < 0:
        years -= 1
        months += 12

    return years, months, days

def get_days_in_month(month, year):
    # Returns the number of days in a given month and year 
    if month == 2:  # February
        if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): 
            return 29  # Leap year
        else:
            return 28
    elif month in [4, 6, 9, 11]:  # April, June, September, November 
        return 30
    else:
        return 31

# User date of birth details
birth_day = int(input("Enter your birth day: "))
birth_month = int(input("Enter your birth month: "))
birth_year = int(input("Enter your birth year: "))

# Current date
current_date = date.today()

# Create date objects for birth date and current date
birth_date = date(birth_year, birth_month, birth_day)

# Check if the birth date is valid
if birth_date <= current_date:
    # Calculate age
    age_years, age_months, age_days = calculate_age(birth_date, current_date)
    print(f"Your age is {age_years} years, {age_months} months, and {age_days} days.")
else:
    print("Please enter a valid date of birth.")

Output-1

Enter your birth day: 17
Enter your birth month: 11
Enter your birth year: 2001
Your age is 21 years, 7 months, and 22 days.

Output-2

Enter your birth day: 25
Enter your birth month: 9
Enter your birth year: 2009
Your age is 13 years, 9 months, and 14 days.

Explanation

It imports the date class from the datetime module, which provides functions for working with dates.

The program defines a function called calculate_age that takes two parameters: birth_date and current_date. This function calculates the age in years, months, and days based on the provided dates.

Within the calculate_age function, it calculates the difference between the current year and the birth year to get the number of years. It also calculates the difference between the current month and the birth month to get the number of months. Similarly, it calculates the difference between the current day and the birth day to get the number of days.

The program then adjusts for any negative differences.For example, if the birth day is greater than the current day, it means the current month hasn’t reached the birth month yet. In this case, it subtracts 1 from the months and adds the number of days in the birth month to the days variable.

Similarly, if the birth month is greater than the current month, it means the current year hasn’t reached the birth year yet. In this case, it subtracts 1 from the years and adds 12 to the months.

The function returns the calculated age as a tuple of years, months, and days.

Another function called get_days_in_month is defined. This function takes the month and year as parameters and returns the number of days in that month. It handles leap years by checking if the month is February and the year is a leap year.

The program prompts the user to enter their birth date details: day, month, and year.
It gets the current date using the date.today() method.

The program creates a date object for the birth date using the provided day, month, and year.

It checks if the birth date is valid by comparing it with the current date. If the birth date is less than or equal to the current date, it means it’s a valid date.

If the birth date is valid, it calls the calculate_age function with the birth date and current date as arguments. It assigns the returned values (years, months, and days) to separate variables.

Finally, it prints the calculated age in years, months, and days using formatted string interpolation. If the birth date is not valid, it displays an error message.

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment