Age in years with python?
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
John is a freelance programmer living in Sydney Australia. He blogs whatever takes his fancy; computing tips, travel letters, and random stuff from his life. He does it primarily to learn and demonstrate the running of a website.
Recent Comments