Python Forum
Simple calculation using datetime
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple calculation using datetime
#1
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)
Reply
#2
This question has a number of answers on stackoverflow
Reply
#3
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020