calculate age from date of birth
I just needed to write a function in python that calculates age from birthday (date of birth). In stackoverflow I found couple of good discussions here and here. I picked up the following code from the later post, as it's very simple and works for my purpose:
def calculate_age(born):
today = date.today()
try:
birthday = born.replace(year=today.year)
except ValueError: # raised when birth date is February 29 and the current year is not a leap year
birthday = born.replace(year=today.year, day=born.day-1)
if birthday > today:
return today.year - born.year - 1
else:
return today.year - born.year
if __name__ == "__main__":
day, month, year = [int(x) for x in "7/11/1982".split("/")]
born = date(year, month, day)
print calculate_age(born)
Comments