Python program to calculate age in year
Given birth date in y/m/d format, write a Python program to find the present age in years.
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.
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.
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.
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:
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).
Please Login to comment...