Kodeclik Logo

Learn More

Fall 2025

Kodeclik Blog

Finding Someone's Age using Python

Let's suppose you are given somebody's birthdate and you desire to find their age. How can you do this easily in Python? While it might seem straightforward to just subtract years, there are important nuances to consider—like whether someone has had their birthday yet this year. In this tutorial, we'll explore how to accurately calculate age using Python's built-in tools.

Python’s Datetime Module

Python's datetime module is a powerful built-in library that helps you work with dates and times. You don't need to install anything extra—it comes standard with Python. The module provides several classes for manipulating dates and times, but for age calculation, we primarily need the date class.

The date class represents a calendar date (year, month, and day) and provides useful methods like today() to get the current date. It also supports arithmetic operations and comparisons, making it perfect for calculating the difference between two dates.

Python code to find age

Computing one’s age

Here's a clean, accurate function to calculate someone's age in years:

from datetime import date

def calculate_age(birthdate):
    """
    Calculate age in years given a birthdate.
    
    Args:
        birthdate: A date object representing the person's birth date
        
    Returns:
        int: The person's age in years
    """
    today = date.today()
    
    # Calculate the difference in years
    age = today.year - birthdate.year
    
    # Adjust if birthday hasn't occurred yet this year
    if (today.month, today.day) < (birthdate.month, birthdate.day):
        age -= 1
        
    return age

# Example usage
birthday = date(1990, 5, 15)
age = calculate_age(birthday)
print(f"Age: {age} years")

This function uses Python's date class from the datetime module to accurately determine a person's age in years, accounting for whether their birthday has occurred in the current year. By comparing today's month and day as a tuple to the birthdate's month and day, the function subtracts one year if the birthday hasn't yet occurred, ensuring the result matches our everyday understanding of age. This approach solves the common mistake of simply subtracting years and avoids errors during edge cases like leap years or birthdays later in the year.​

The key insight here is the comparison (today.month, today.day) < (birthdate.month, birthdate.day). Python compares tuples element by element, so this checks if today's month/day comes before the birth month/day. If it does, the person hasn't had their birthday yet this year, so we subtract one from the age.

Computing one’s age from user input

We can update the above program to ask for user input and compute one’s age from that input:

from datetime import date
def get_age_from_input():
    """Get birthdate from user and calculate age."""
    print("Enter your birthdate:")
    year = int(input("Year (e.g., 1990): "))
    month = int(input("Month (1-12): "))
    day = int(input("Day (1-31): "))
    
    birthdate = date(year, month, day)
    age = calculate_age(birthdate)
    
    return age

# Example usage
# user_age = get_age_from_input()
# print(f"You are {user_age} years old")

This code extends the age calculation to interactive use, allowing users to input their birth year, month, and day. By converting these inputs to integers and constructing a date object, the code leverages the previously defined calculate_age function to compute age based on live input. It demonstrates how user interaction works in Python and reinforces the utility of class methods for accepting real-world data.

Things to watch out for

When using date.today(), Python uses your system's local timezone. This is usually what you want for age calculations, since we typically think of age in terms of our local calendar day. However, if you're building an application that serves users across different time zones, you need to keep several things in mind.

  • Different "today" values: A person born on January 1, 2000, might be different ages depending on whether it's currently January 1st in their timezone. If it's 11 PM on December 31st in New York but already January 1st in Sydney, two users could have different ages.
  • Server vs. user timezone: If your code runs on a server in one timezone but serves users in another, date.today() will use the server's timezone. For user-facing applications, you might want to pass the user's local date explicitly.

If timezone precision matters, consider passing the current date as a parameter rather than using date.today() inside the function:

def calculate_age(birthdate, current_date=None):
    """Calculate age with optional current date parameter."""
    if current_date is None:
        current_date = date.today()
    
    age = current_date.year - birthdate.year
    if (current_date.month, current_date.day) < (birthdate.month, birthdate.day):
        age -= 1
    return age

Checking for Invalid Dates

Always validate user input when accepting birthdates. The date() constructor will raise a ValueError for invalid dates:

try:
    birthdate = date(2000, 2, 30)  # February 30th doesn't exist!
except ValueError as e:
    print(f"Invalid date: {e}")

This snippet warns that the Python date() constructor will raise a ValueError if passed an invalid date, such as February 30th. It's essential to validate user input before constructing date objects. This check prevents your program from crashing and allows you to display helpful error messages, promoting good coding practices in handling user input.

Checking for Future Dates

What happens if someone enters a future birthdate? Our function would return a negative age. You might want to add validation:

def calculate_age(birthdate):
    today = date.today()
    
    if birthdate > today:
        raise ValueError("Birthdate cannot be in the future")
    
    age = today.year - birthdate.year
    if (today.month, today.day) < (birthdate.month, birthdate.day):
        age -= 1
    return age

The updated function raises a ValueError if the provided birthdate comes after the current date, preventing illogical results (like negative ages) if a user submits a future birthdate. This validation ensures the integrity of age calculations and helps guide users towards correcting mistakes before proceeding with other logic or calculations in your program.

Applications

Age calculation has numerous practical applications in software development. For instance, in age verification systems many services need to verify that users meet minimum age requirements:

def can_get_drivers_license(birthdate, state_minimum_age=16):
    """Check if someone is old enough to get a driver's license."""
    age = calculate_age(birthdate)
    return age >= state_minimum_age

# Example
birthday = date(2008, 3, 15)
if can_get_drivers_license(birthday):
    print("Eligible for driver's license!")
else:
    eligible_date = date(birthday.year + 16, birthday.month, birthday.day)
    print(f"Eligible on: {eligible_date}")

As another example, insurance premiums and retirement planning often depend on age:

def calculate_insurance_rate(birthdate, base_rate=100):
    """Calculate insurance rate based on age (simplified example)."""
    age = calculate_age(birthdate)
    
    if age < 25:
        multiplier = 1.5  # Higher rate for young drivers
    elif age < 65:
        multiplier = 1.0  # Standard rate
    else:
        multiplier = 1.2  # Slightly higher for seniors
    
    return base_rate * multiplier

Finally, events like marathons or competitions often have age categories:

def get_race_category(birthdate, race_date):
    """Determine race age category."""
    age = calculate_age(birthdate)
    
    if age < 18:
        return "Youth"
    elif age < 30:
        return "Open 18-29"
    elif age < 40:
        return "Masters 30-39"
    elif age < 50:
        return "Masters 40-49"
    else:
        return "Masters 50+"

All the above examples demonstrate practical uses for age calculation functions. The can_get_drivers_license example checks if someone meets the age requirement for a driver's license, using age as a gatekeeper for eligibility. The insurance rate example shows how age can determine premiums—young drivers and seniors pay different rates. Finally, age categories for races or competitions rely on accurate age computation to place participants in fair divisions. Together, these cases illustrate age calculation in everyday applications.

Summary

Calculating age in Python is straightforward with the datetime module, but accuracy matters. The most important thing to remember is that you can't just subtract years—you need to account for whether the birthday has occurred yet this year. Python's built-in datetime.date class provides all the tools you need for reliable date handling, including the ability to compare dates and get the current date. When building applications that serve users across different locations, be mindful of timezone considerations, and always validate input to handle edge cases like invalid or future dates.

With the code examples provided in this tutorial, you can confidently implement age calculation in your Python projects. Age calculation powers countless real-world applications, from age verification systems and driver's license eligibility checks to insurance rate calculations and healthcare screening recommendations. Whether you're building a content restriction system, determining event categories, or calculating eligibility for various services, you now have the tools to do it accurately and reliably.

Enjoy this blogpost? Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2025. All rights reserved.