Python Program to Calculate Age in Years Months and Days

age calculator program in python

Introduction

In the world of programming, there are countless real-life scenarios where the need to calculate someone’s age arises. Whether you’re building a personal information management system or a health-tracking application, an age calculator program can be an invaluable tool. In this article, we will explore how to create an age calculator program using Python to calculate age in years, months, and days.

Python is a versatile and beginner-friendly programming language that provides a wide range of tools and libraries for various tasks. To get started, make sure you have Python installed on your system. Once you’re ready, let’s dive into the process of creating the age calculator program step by step.

Import the Required Libraries

To create an age calculator program, we need to use the `datetime` module in Python, which provides classes for manipulating dates and times. Open your favorite Python editor or IDE and begin by importing the necessary libraries:

from datetime import date

Define a Dictionary

Create a Python Dictionary `Months` to hold the total number of days as the corresponding key value for each month.

Months = {
    1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31,
    8:31, 9:30, 10:31, 11:30, 12:31
}

Check Leap Year

To check whether the given year is a leap year or not, define a function with the name `is_leap_year`. This function will return a boolean value based on the outcome.

def is_leap_year(year):
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False

Define the Age Calculation Function

Next, let’s define a function called `calculate_age` that will take the user’s birth date as input and return their age in years, months, and days:

def calcluate_age(date1, date2):
    # Differnce between two dates/Total no. of days
    TotalDays = (date2 - date1).days

    # If birth year and current year are the same
    if int(year1) == int(year2):
        month = TotalDays/30
        day = TotalDays%30
        year = 0
    else:
        year = TotalDays/365
        month = (TotalDays%365)/30

        # Check if the given year is a leap year or not.
        # If Yes, then Make the total number of days 
        # in the month of February 29.
        if is_leap_year(int(year2)):
            Months[2] = 29
            
        if int(day2) >= int(day1):
            day = int(day2) - int(day1)

        # If the current month is February and the 
        # current year is a leap year or not
        elif int(mon2) == 2 and (is_leap_year(int(year2)) or (not is_leap_year(int(year2)))):
            year = year
            month = 11

            # Check if the current month is January or Not
            if int(mon2) == 1:
                prevMonth = Months[int(mon2)]
            else:
                prevMonth = Months[int(mon2)-1]
            days = prevMonth - int(day1) + int(day2)
            day = days
        else:
            if int(mon2) == 1:
                prevMonth = Months[int(mon2)]
            else:
                prevMonth = Months[int(mon2)-1]
            days = prevMonth - int(day1) + int(day2)
            day = days
            month = month
    
    # Printing the result
    print("YOUR Age is: ",int(year),"years ", int(month), "months ", int(day), "days")

In this function, we calculate the age by subtracting the birth date from the current date. In addition, we examine numerous conditions in this section and proceed with appropriate actions based on them. Here are the following:

  1. If the current year and the birth year are the same or not.
  2. If step 1 is false, we calculate the number of years and months.
  3. Subsequently, we verify whether the current year is a leap year or not. If it is, we update the number of days for February to 29 in the `Months` dictionary.
  4. If the provided date (the day number within that month) is greater than the birth date, the Total Number of Days can be easily determined, and the result is displayed.
  5. If step 4 is false, we then proceed to verify if the current month is February and if the current year is a leap year or not.
  6. Based on the outcome of step 5, we incorporate two additional consecutive conditions in order to obtain an accurate result.
  7. In the end, the function prints the age in years, months, and days.

Putting it All Together

The main part of the program takes the input from the user, converts the given date into date format, and calls the `calculate_age` function.

if __name__ == "__main__":
    # Collecting the inputs from the user
    print("Date Format: dd/mm/yyyy")
    day1, mon1, year1=input("Please Enter Your Birth Date: ").split('/')
    day2, mon2, year2=input("Please Enter The Current Date: ").split('/')

    # Converting given dates into date format
    date1 = date(int(year1), int(mon1), int(day1))
    date2 = date(int(year2), int(mon2), int(day2))

    calcluate_age(date1, date2)

Run the Program

Save the Python file with a `.py` extension, such as `age_calculator.py`, and run it. You should see the program prompt you to enter your birth date and the current date. After providing the input, the program will display your age in years, months, and days.

Output

Date Format: dd/mm/yyyy
Please Enter Your Birth Date: 02/10/1996
Please Enter The Current Date: 30/06/2023
YOUR Age is: 26 years 9 months 28 days

Summary

In this article, we explored how to create an age calculator program using Python. We used the `datetime` module to perform date calculations and developed a simple function to calculate age in years, months, and days. The program displays the age in a user-friendly format. This age calculator can be a useful tool for a variety of applications,
such as age verification in registration processes or for personal
record-keeping, etc.

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 147

Leave a Reply

Your email address will not be published. Required fields are marked *