Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to calculate age in year
Generally, the age of a person is calculated by subtracting the birth year from the current year. In Python, we can calculate age more precisely using modules like datetime, dateutil, and timedelta to handle dates properly.
Basic Age Calculation
The simplest approach uses basic arithmetic ?
Current year - Birth year
Example
This example implements the basic method by passing current year and birth year to a function ?
def age_calculator(current_year, birth_year):
age = current_year - birth_year
print("The age of the person in years is", age, "years")
age_calculator(2023, 1995)
The age of the person in years is 28 years
However, this method doesn't account for whether the birthday has occurred this year. Let's explore more accurate methods.
Using datetime Module
The datetime module provides date.today() to get the current date and calculate age more accurately by considering the birth month and day ?
import datetime
birthdate = "14-05-1991"
day, month, year = map(int, birthdate.split("-"))
today = datetime.date.today()
# Check if birthday has occurred this year
age = today.year - year - ((today.month, today.day) < (month, day))
print("Your age is", age, "years.")
Your age is 32 years.
Using dateutil relativedelta
The dateutil module provides relativedelta() function to calculate the exact difference between two dates ?
from dateutil.relativedelta import relativedelta
import datetime
birthdate = "22-01-1995"
birthdate = datetime.datetime.strptime(birthdate, '%d-%m-%Y').date()
today = datetime.date.today()
age = relativedelta(today, birthdate).years
print("Your age is", age, "years.")
Your age is 28 years.
Using timedelta Function
The timedelta() function calculates the number of days between two dates and divides by the average days per year (365.2425) ?
import datetime
def age_calculator(birthdate):
today = datetime.date.today()
age = (today - birthdate) // datetime.timedelta(days=365.2425)
return age
birthdate = datetime.date(1991, 5, 14)
age = age_calculator(birthdate)
print("The age of the person in years is", age, "years")
The age of the person in years is 32 years
Comparison
| Method | Accuracy | Best For |
|---|---|---|
| Basic subtraction | Approximate | Quick calculations |
| datetime module | Exact | Most common use cases |
| dateutil.relativedelta | Exact | Complex date calculations |
| timedelta | Very precise | Scientific applications |
Conclusion
Use the datetime module for most age calculations as it accounts for birth month and day. For more complex date operations, use dateutil.relativedelta which provides the most readable and accurate results.
