Calculating age in Python
Here’s the Python method I was using to calculate someone’s age from a date object:
def calculateAge(born):
"""Calculate the age of a user."""
today = date.today()
birthday = date(today.year, born.month, born.day)
if birthday > today:
return today.year - born.year - 1
else:
return today.year - born.year
If you’re into Python you might just like to see if you spot the bug in this code — I didn’t!
Anyway, today we had an active user on the site who was born on February 29 in a leap year. And of course, that is the bug in the code I was using. I fixed it by adding an exception handler:
try:
birthday = date(today.year, born.month, born.day)
except ValueError:
# Raised when person was born on 29 February and the current
# year is not a leap year.
birthday = date(today.year, born.month, born.day - 1)