Given someone’s date of birth how do I work out their age? This is actually less trivial than first appears because:
- the person’s age doesn’t increment until their birthday passes on the calendar
- that day is not always the same period of time after midnight on the 1st of January
This solution works by asking if today’s month is before their birthday, and if their birthday is this month whether today’s date is before the birth day.
This works even if they are born on the 29th of Feb.
def age(dob):
import datetime
today = datetime.date.today()
if today.month < dob.month or \
(today.month == dob.month and today.day < dob.day):
return today.year - dob.year - 1
else:
return today.year - dob.year
>>> import datetime
>>> datetime.date.today()
datetime.date(2009, 12, 1)
>>> age(datetime.date(2008, 11, 30))
1
>>> age(datetime.date(2008, 12, 1))
1
>>> age(datetime.date(2008, 12, 2))
0
Thanks for your code.
if self.dob > today(year=self.dob.year):
return today.year - self.dob.year - 1
return today.year - self.dob.year