Python: how to calculate the age of a user

In this article we will see how to calculate the age of a user from his birth date with Python.

The first criterion to establish is the format of the date. We decide to use the standard format YYYY-mm-dd in order to prepare the code for future use in a web environment.

We must initially validate this format and then verify that the date is not in the future, which would effectively make the calculation completely wrong.

We will use regular expressions and the datetime core module to implement the validation step.

import re
import sys
from datetime import datetime

def is_valid_birthday(date_str=''):
    valid = True
    reg = re.compile(r'^\d{4}-\d{2}-\d{2}$')
    if not reg.search(date_str):
        valid = False
        return valid
    format_dt = '%Y-%m-%d'
    try:
        dt = datetime.strptime(date_str, format_dt)
    except ValueError:
        valid = False
        return valid
    now = datetime.now()
    if dt > now:
        valid = False
    return valid

We have deliberately inserted a possible redundancy to show how format validation can take place both superficially (pattern matching) and deeply (the datetime.strptime() method). After this validation we can compare the current date with the date provided: if this date is greater than the current one, the validation fails.

At this point it is necessary to calculate the difference between the two dates with a timedelta object.

def get_dates_diff_delta(dt_str):
    dt = datetime.strptime(dt_str, '%Y-%m-%d')
    return datetime.now() - dt

This object has the days property which indicates the elapsed days but does not have a property for elapsed years. Knowing that a year is made up of 365 days, we can carry out the following calculation by converting the result into an integer.

def get_years_from_delta(d):
    days_in_year = 365
    return int(d.days / days_in_year)

Our code will run as follows:

def main():
    input_date = input('Insert your birth date (YYYY-mm-dd)')
    is_valid = is_valid_birthday(input_date)
    if not is_valid:
        print('Invalid date')
        sys.exit(1)
    years = get_years_from_delta(get_dates_diff_delta(input_date))
    print(f'You are {years} years old')
    sys.exit(0)


if __name__ == '__main__':
    main()
Back to top