Python Tutorial: An Age Calculator Project In Python With Source Code

Learn how to calculate age in Python using the datetime module. This guide covers converting string dates with strptime() and provides a detailed Python program to calculate age in years, months, weeks, and days.
Python Tutorial: An Age Calculator Project In Python With Source Code

In Python programming, working with dates and times is crucial in many applications. Whether you’re building a reminder app, an event scheduler, or simply calculating someoneā€™s age, the datetime module in Python offers robust tools to handle all sorts of time-based data.

In this post, weā€™ll explore how to create a simple Python program that accepts a userā€™s name and date of birth and then calculates how old they are, breaking down the age in years, months, weeks, and days. Along the way, weā€™ll dive deeper into an important function called strptime() that allows us to convert string representations of dates into usable date objects.

Letā€™s get started!

Why Calculate Age in Python?

Knowing how to calculate someone’s age from a date of birth is useful in various fields:

  • Apps and websites: User profiles often require age-based services or content, such as age-restricted material.
  • Medical apps: Tracking someone’s health or prescriptions could rely on their age.
  • Event applications: Calculating exact days, weeks, or years until significant events like anniversaries, birthdays, or deadlines.

Using Python, this becomes an efficient task.

The Python Program

Below is the Python code that accepts the userā€™s name and date of birth, then calculates and displays their age in different units (years, months, weeks, and days):

from datetime import datetime

# Function to calculate age
def calculate_age(birthdate):
    today = datetime.today()

    # Calculate years
    years = today.year - birthdate.year
    if today.month < birthdate.month or (today.month == birthdate.month and today.day < birthdate.day):
        years -= 1  # If birthday hasn't occurred yet this year

    # Calculate months
    months = today.month - birthdate.month
    if today.day < birthdate.day:
        months -= 1  # Adjust if birthday hasn't passed this month
    if months < 0:
        months += 12

    # Calculate days
    delta_days = (today - birthdate).days
    weeks = delta_days // 7  # Calculate weeks from total days

    return years, months, weeks, delta_days

# Input user's name and birthdate
name = input("Enter your name: ")
birthdate_str = input("Enter your date of birth (YYYY-MM-DD): ")
birthdate = datetime.strptime(birthdate_str, "%Y-%m-%d")

# Call the function to calculate age
years, months, weeks, days = calculate_age(birthdate)

# Display the result
print(f"\nHello {name}! Here is your age breakdown:")
print(f"You are {years} years, {months} months old.")
print(f"That's approximately {weeks} weeks or {days} days old.")

This program does several things:

  1. Accepts input: The program first prompts the user for their name and birthdate.
  2. Uses strptime to convert input: The userā€™s input date is a string, so we convert it into a datetime object using datetime.strptime().
  3. Calculates the age: The program then calculates the difference between todayā€™s date and the userā€™s birthdate in years, months, weeks, and days.
  4. Displays the results: Finally, it prints out the results in a clear and user-friendly format.

Breaking Down the Code: strptime()

One of the key elements of this program is the strptime() method from Pythonā€™s datetime module. So, what exactly does it do?

What is strptime?

The strptime() method stands for string parse time. It is used to convert a string representation of a date into a datetime object that Python can work with.

For example, letā€™s say you enter your birthdate as a string in this format: "1990-05-15". In Python, this is just a string, so we canā€™t perform any date-based calculations on it. With strptime(), we can convert this string into a datetime object that knows the actual day, month, and year.

Hereā€™s how it works:

birthdate_str = "1990-05-15"
birthdate = datetime.strptime(birthdate_str, "%Y-%m-%d")
  • The first argument is the date string, which in this case is "1990-05-15".
  • The second argument is the format specifier "%Y-%m-%d", which tells Python how to interpret the string.

Understanding the Format: "%Y-%m-%d"

The format string "%Y-%m-%d" is crucial in parsing the date correctly. Hereā€™s what it means:

  • %Y: The year, represented by four digits. For example, 1990 or 2023. Also make sure the Y is capital letter
  • %m: The month, represented by two digits (01 to 12), where January is 01, February is 02, and so on.
  • %d: The day of the month, represented by two digits (01 to 31).

Together, this format ensures that the input string "1990-05-15" will be interpreted as May 15, 1990.

Using Age Calculations in Real Applications

In our program, we calculate age not only in years but also in months, weeks, and days. This is useful when you need more precise age measurements. For example:

  • Babies and toddlers: Age is often tracked in months or even days.
  • Specific countdowns: If you need to know how many weeks or days are left until a specific date (like a milestone), this calculation will come in handy.

The program even adjusts for cases where the user’s birthday hasnā€™t occurred yet in the current year or month, ensuring accurate calculations.

Conclusion

By leveraging Pythonā€™s datetime module and the powerful strptime() function, you can easily convert string dates and perform detailed age calculations. This simple yet versatile tool can serve as the foundation for many date-related projects, from event scheduling to birthday reminders.

With just a few lines of code, you can calculate not only someoneā€™s age in years but also how old they are in days, weeks, and months.

Feel free to modify this program for your own projectsā€”whether you’re building a user-based platform or just having fun with Python!

With Python’s flexibility, date and time management becomes a powerful tool in your programming toolkit. Have any questions or want to know more? Leave a comment or share this post with your friends!

Yakubu Binuyaminu
Yakubu Binuyaminu

I am a product designer and tech enthusiast, I love writing about technology and sharing my experiences with my blog readers, I am one of the co founders of this amazing platform.

We will be happy to hear your thoughts

Leave a reply

Aqila.ng
Logo
Compare items
  • Total (0)
Compare
0
Shopping cart