Python program to calculate age in year
Last Updated :
14 Mar, 2023
Given birth date in y/m/d format, write a Python program to find the present age in years.
Examples:
Input : 1997/2/3
Output : 21 years (for present year i.e 2018)
Input : 2010/12/25
Output : 8 years (for present year i.e 2018)
Approach # 1:
The naive approach to find the current age in years is to find the difference between the current year and birth year. Refer the Naive approach from here.
Approach #2: Using datetime module
Python provides datetime module to deal with all datetime related issues in python. Using datetime we can find the age by subtracting birth year from current year. Along with this, we need to focus on the birth month and birthday. For this, we check if current month and date are less than birth month and date. If yes subtract 1 from age, otherwise 0.
Python3
from datetime import date
def calculateAge(birthDate):
today = date.today()
age = today.year - birthDate.year -
((today.month, today.day) <
(birthDate.month, birthDate.day))
return age
print (calculateAge(date( 1997 , 2 , 3 )), "years" )
|
The time complexity of the provided code is O(1) as it involves basic arithmetic operations and date comparisons.
The auxiliary space complexity of the code is O(1) as it only uses a constant amount of extra space to store the today object, age variable, and the boolean result of the date comparison.
Approach #3 : Efficient datetime approach
The above approaches do not deal with a special case i.e. when birth date is February 29 and the current year is not a leap year. This case has to be raised as an exception because the calculation of birthdate may be inaccurate. This method includes try and catch for this exception.
Python3
from datetime import date
def calculateAge(born):
today = date.today()
try :
birthday = born.replace(year = today.year)
except ValueError:
birthday = born.replace(year = today.year,
month = born.month + 1 , day = 1 )
if birthday > today:
return today.year - born.year - 1
else :
return today.year - born.year
print (calculateAge(date( 1997 , 2 , 3 )), "years" )
|
Approach #4: Using division
In this approach, we calculate the number of date from the birth date till current date. Divide the number of date by the days in a year i.e 365.2425.
Python3
from datetime import date
def calculateAge(birthDate):
days_in_year = 365.2425
age = int ((date.today() - birthDate).days / days_in_year)
return age
print (calculateAge(date( 1997 , 2 , 3 )), "years" )
|
Time complexity: O(1)
Auxiliary space: O(1)
Approach #5 : Use dateutil module
To install dateutil, you can use the following pip command:
pip install python-dateutil
This will install the dateutil library, which provides a powerful set of tools for manipulating dates and times in Python. You can then use the library in your Python code by importing it.
One approach is to use the relativedelta function from the dateutil module. This function allows you to calculate the difference between two dates in terms of years, months, days, etc. Here is an example of how you can use it to calculate the age in years:
Python3
from dateutil.relativedelta import relativedelta
from datetime import date
def calculate_age(birth_date):
today = date.today()
age = relativedelta(today, birth_date)
return age.years
birth_date = date( 1997 , 2 , 3 )
age = calculate_age(birth_date)
print (f "Age in years: {age}" )
|
Output:
Age in years: 25
Time Complexity: The time complexity of this program is O(1) because the execution time of this program does not depend on the input size.
Auxiliary Space: The program uses a constant amount of auxiliary space, regardless of the input size. The auxiliary space used by this program is O(1).
This approach has the advantage of being able to handle cases where the birth date is in the future or the current date is not a valid date (e.g. February 29 in a non-leap year). It also allows you to easily calculate the age in other units, such as months or days, by simply accessing the corresponding attribute of the relativedelta object (e.g. age.months or age.days).
Similar Reads
Python Program to Check Leap Year
We are given a year we need to find whether given year is leap year or not. For example, y = 2000 is given year we need to find whether given year is leap year or not so that resultant output should be 'Leap year'. Using Nested ConditionsUsing nested conditions in Python involves placing one if stat
3 min read
Python program to calculate Date, Month and Year from Seconds
Given the number of seconds, the task is to write a Python program to calculate the date, month, and year in the format MM-DD-YYYY that have been passed from 1 January 1947. Examples Input: 0 Output: 01-01-1947 Input: 123456789 Output: 11-29-1950 Input: 9876543210 Output: 12-22-2259Approach to Calcu
4 min read
Python program to print calendar of given year
Given a valid year as input, write a Python program to print the calendar of given year. In order to do this, we can simply use calendar module provided in Python. For more details about calendar module, refer this article. # Python program to print calendar for given year # importing calendar libra
3 min read
Python program to print current year, month and day
In this article, the task is to write a Python Program to print the current year, month, and day. Approach: In Python, in order to print the current date consisting of a year, month, and day, it has a module named datetime. From the DateTime module, import date classCreate an object of the date clas
1 min read
Python program to find the first day of given year
Given a year as input, write a Python to find the starting day of the given year. We will use the Python datetime library in order to solve this problem. Example: Input : 2010 Output :FridayInput :2019 Output :Tuesday Below is the implementation: C/C++ Code # Python program to find the first day of
2 min read
Python Program to Print the Incremented Date if valid
In this article, we will write a python program to input a date and check whether it is a valid date or not. If it is valid, output the incremented date. Otherwise, print âInvalid dateâ. Examples: Input : 1/2/2000 Output: 2/2/2000 Input : 29/2/2002 Output: Invalid date Input : 31/12/2015 Output: 1/1
3 min read
Make a Simple Calculator - Python
In this article, we will create a simple calculator that can perform basic arithmetic operations like addition, subtraction, multiplication and division. We will explore two implementations for the same: Command-Line CalculatorGUI-Based Calculator using TkinterCommand-Line CalculatorThis version of
3 min read
Python Program to Compute Life Path Number
Given a String of date of format YYYYMMDD, our task is to compute the life path number. Life Path Number is the number obtained by summation of individual digits of each element repeatedly till single digit, of datestring. Used in Numerology Predictions. Examples: Input : test_str = "19970314" Outpu
4 min read
Python - Convert day number to date in particular year
Given day number, convert to date it refers to. Input : day_num = "339", year = "2020" Output : 12-04-2020 Explanation : 339th Day of 2020 is 4th December. Input : day_num = "4", year = "2020" Output : 01-04-2020 Explanation : 4th Day of 2020 is 4th January. Method #1 : Using datetime.strptime() In
5 min read
Python program to print Calendar without calendar or datetime module
Given the month and year. The task is to show the calendar of that month and in the given year without using any module or pre-defined functions. Examples: Input : mm(1-12) :9 yy :2010 Output : September 2010 Su Mo Tu We Th Fr Sa 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 2
3 min read