Skip to content

Instantly share code, notes, and snippets.

@prestontimmons
Created May 6, 2010 18:00
Show Gist options
  • Save prestontimmons/392466 to your computer and use it in GitHub Desktop.
Save prestontimmons/392466 to your computer and use it in GitHub Desktop.
Calculate age from a given date
from datetime import date
import unittest
def calculate_age(birth_date, until=None):
"""
Calculates the age of a person from their birth date to a given
date, accounting for birth dates during leap year. The date
defaults to today if no date is specified.
"""
until = until or date.today()
try:
birthday = date(until.year, birth_date.month, birth_date.day)
except ValueError:
birthday = date(until.year, birth_date.month, birth_date.day - 1)
if birthday > until:
return until.year - birth_date.year - 1
else:
return until.year - birth_date.year
class CalculateAgeTest(unittest.TestCase):
def test_calculate_age(self):
data = [
# test normal dates
[
date(year=1982, month=11, day=26),
date(year=2000, month=11, day=25),
17,
],
[
date(year=1982, month=11, day=26),
date(year=2000, month=11, day=26),
18,
],
# test leap year
[
date(year=1996, month=2, day=29),
date(year=2000, month=2, day=26),
3,
],
[
date(year=1996, month=2, day=29),
date(year=2000, month=2, day=29),
4,
],
[
date(year=1996, month=2, day=29),
date(year=2001, month=3, day=1),
5,
],
]
for entry in data:
self.assertEqual(calculate_age(entry[0], entry[1]), entry[2])
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment