Skip to content

Instantly share code, notes, and snippets.

@higs4281
Last active May 2, 2019 02:43
Show Gist options
  • Save higs4281/16adc129cbde3675e24f1557847f21ac to your computer and use it in GitHub Desktop.
Save higs4281/16adc129cbde3675e24f1557847f21ac to your computer and use it in GitHub Desktop.
Current age
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