Created
January 26, 2013 08:17
-
-
Save josephtate/4641000 to your computer and use it in GitHub Desktop.
An age calculating library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import calendar | |
def simple_age(birthdate, today=None): | |
if today is None: | |
today = datetime.date.today() | |
#what's this year's birthdate? | |
try: | |
bd = datetime.date(today.year, birthdate.month, birthdate.day) | |
except ValueError: | |
#special case 2/29 | |
bd = datetime.date(today.year, 3, 1) | |
if bd <= today: | |
return today.year - birthdate.year | |
else: | |
return today.year - birthdate.year - 1 | |
def get_age(birthdate,today=None): | |
start_year = birthdate.year | |
if today is None: | |
today = datetime.date.today() | |
current_year = today.year | |
# without modification, calling leapdays will return number of leap days | |
# between jan1 start_year and jan 1 current_year | |
if calendar.isleap(start_year) and birthdate >= datetime.date(start_year, 2, 29): | |
start_year += 1 | |
if calendar.isleap(current_year) and today >= datetime.date(current_year, 2, 29): | |
# if we are past the leap day, we should count the current year's leap day also | |
current_year += 1 | |
leapdays = calendar.leapdays(start_year, current_year) | |
return ((today - birthdate).days - leapdays)/ 365 | |
#get_age = simple_age | |
assert(8 == get_age(datetime.date(1992, 2, 29), datetime.date(2000, 2, 29))) | |
assert(8 == get_age(datetime.date(1992, 2, 28), datetime.date(2000, 2, 28))) | |
assert(8 == get_age(datetime.date(1992, 3, 1), datetime.date(2000, 3, 1))) | |
assert(8 == get_age(datetime.date(1992, 2, 29), datetime.date(2000, 3, 1))) | |
assert(8 == get_age(datetime.date(1992, 2, 28), datetime.date(2000, 3, 1))) | |
assert(7 == get_age(datetime.date(1992, 3, 1), datetime.date(2000, 2, 28))) | |
assert(7 == get_age(datetime.date(1992, 3, 1), datetime.date(2000, 2, 29))) | |
assert(9 == get_age(datetime.date(1992, 2, 28), datetime.date(2001, 2, 28))) | |
assert(9 == get_age(datetime.date(1992, 3, 1), datetime.date(2001, 3, 1))) | |
assert(9 == get_age(datetime.date(1992, 2, 29), datetime.date(2001, 3, 1))) | |
assert(9 == get_age(datetime.date(1992, 2, 28), datetime.date(2001, 3, 1))) | |
assert(8 == get_age(datetime.date(1992, 3, 1), datetime.date(2001, 2, 28))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment