Calculate age in years and days

In this example, the Python datetime module is used to calculate and output the number of days and years of a birth date.

import datetime


def calculateAge(birthday):
    (d, m, y) = birthday.split('.')
    return d, m, y


birthday = str(
    input("Please enter your birthday in following format dd.mm.yyyy:  "))
today = datetime.datetime.now()

splittedDate = calculateAge(birthday)
birthdayDate = datetime.datetime(
    int(splittedDate[2]), int(splittedDate[1]), int(splittedDate[0]))

age = (today - birthdayDate).days

print(repr(age) + " days old")
print(repr(int(age/365)) + " years old")
Code Explanation
Importing the datetime Module

The script begins by importing the datetime module, which provides various functions and classes to manipulate dates and times.

Defining the calculateAge Function
  • calculateAge(birthday): This function is designed to take a birthday string in the format “dd.mm.yyyy” and split it into day, month, and year. The split result is a tuple containing day (d), month (m), and year (y), extracted from the birthday string using the split('.') method.
Input from User
  • birthday: This variable collects the user’s birthday via input, prompting them to enter their birth date in the format “dd.mm.yyyy”. This input is then passed as a string to further processing functions.
Getting the Current Date
  • today: This variable is assigned the current date and time up to the microsecond using datetime.datetime.now(). This provides the reference point from which the age will be calculated.
Calculating Age
  • splittedDate: This variable stores the tuple returned by calculateAge(birthday), which contains the birthday split into day, month, and year.
  • birthdayDate: This datetime object is constructed using the year, month, and day extracted from splittedDate. The values are converted to integers to match the expected data types for creating a datetime object.
  • age: The age in days is calculated by subtracting birthdayDate from today and extracting the .days attribute from the resulting timedelta object.
Printing the Results
  • print(repr(age) + " days old"): This prints the age in days by converting age (which is an integer) to its string representation using repr().
  • print(repr(int(age/365)) + " years old"): This calculates the approximate age in years by dividing the age in days by 365 and then prints it. The division result is converted to an integer for a clean whole number representation of years.
Output
Please enter your birthday in following format dd.mm.yyyy:  10.01.1993
10925 days old
29 years old