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
This entry was posted in geek and tagged , . Bookmark the permalink.

2 Responses to Age in years with python?

  1. Dingo says:

    Thanks for your code.


  2. if self.dob > today(year=self.dob.year):
    return today.year - self.dob.year - 1
    return today.year - self.dob.year

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>