Age calculator in Python
In this post, you will learn how to calculate the present age in years using the Python programming language.
Such a type of question is generally asked in a programming interview. Calculating age is a very simple process. We will have to find the difference between the current year and the birth year. Python provides various approaches to calculate the age. Here, we have mentioned most of them.
Python age calculator Using datetime module
Python provides an inbuilt datetime module. It has several classes that provide a number of functions to deal with dates, times, and time intervals. To calculate the age, we simply subtract the birth year from the current year. To implement this, we need to check if the current month and date are less than the birth month and date. If it is, subtract 1 from the age, otherwise 0.
# Python3 program to calculate age in years
from datetime import date
def calculateAge(dob):
today = date.today()
age = today.year - dob.year -((today.month, today.day) <
(dob.month, dob.day))
return age
print(calculateAge(date(2017, 9, 18)), " years old")
Output of the above code:
3 years old
Python age calculator using division
In this process, we find the numeric value of the date from the birth date to the current date. To convert the number of days in the year, simply divide the number of dates by the number of days in a year.
# Python program to calculate age in years
from datetime import date
def calculate_age(dob):
days_in_year = 365.2425
age = int((date.today() - dob).days / days_in_year)
return age
print(calculate_age(date(1989, 7, 1)), " years old")
Output of the above code:
32 years old
Related Articles
Bubble sort program in Python
Factorial using recursion in Python
Python intersection of lists
Matrix subtraction in Python
Python program to check leap year
Python program to reverse a string
Convert a string to a float in Python
Check if two strings are anagrams Python
Python add list to list
Python Pandas Dataframe to CSV
Python compare two lists
Remove element from list Python
Python iterate list with index
Python program to sum all the numbers in a list
Python print without newline
Python iterate list with index
Python add list to list
Python convert xml to dict
Dictionary inside list python
Python convert dict to xml
Python weather api
Python raise keyword