Age from birthdate in python
How can I find an age in python from today's date and a persons birthdate? The birthdate is a from a DateField in a Django model.
That can be done much simpler considering that int(True) is 1 and int(False) is 0:
from datetime import date
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
from datetime import date
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, month=born.month+1, day=1)
if birthday > today:
return today.year - born.year - 1
else:
return today.year - born.year
Update: Use Danny's solution, it's better