Python Forum
Simple calculation using datetime - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Simple calculation using datetime (/thread-32389.html)



Simple calculation using datetime - mapypy - Feb-06-2021

Hi, How can i calculate age using date time without hardcoding current year? The way I want to solve and validate is as follows:
from datetime import date

def get_age(birth_year):
    """
    returns the age based on current year
    """
    current_year = date.today().year
    
    return 
validate age:


assertion('12a', get_age(1950), 71)
assertion('12b', get_age(1990), 31)
assertion('12c', get_age(2020), 1)



RE: Simple calculation using datetime - Serafim - Feb-06-2021

This question has a number of answers on stackoverflow


RE: Simple calculation using datetime - Jeff900 - Feb-06-2021

In fact, the way you try to do this (with only the birthyear), will not always give the exact result. Because it will basically look to the age the subject will reach the particular year. But besides of that, the following code would do the trick right?

def get_age(birth_year):
    """
    returns the age based on current year
    """
    diff = date.today().year - birth_year
    return diff
To get the exact date you should also use the month and day in your calculation. You can simply calculate a datetime.date object with another datetime.date object. It will return a timedelta object.