Last active
May 2, 2019 02:43
-
-
Save higs4281/16adc129cbde3675e24f1557847f21ac to your computer and use it in GitHub Desktop.
Current age
This file contains hidden or 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 | |
from dateutil import parser | |
def current_age(birth_date): | |
"""Return current age for a string or datetime.date birth date.""" | |
if isinstance(birth_date, datetime.date): | |
dob = birth_date | |
else: | |
dob = parser.parse(birth_date).date() | |
today = datetime.date.today() | |
this_year = today.year | |
try: | |
birthday = dob.replace(year=this_year) | |
except ValueError: # raised when dob is Feb 29 in a non-leap year | |
birthday = dob.replace( | |
year=this_year, day=dob.day - 1) | |
if birthday > today: | |
return this_year - dob.year - 1 | |
else: | |
return this_year - dob.year |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment