Python's way of getting the age based on the date of birth

  • 2020-04-02 14:47:22
  • OfStack

This example shows how python gets the age based on the date of birth. Share with you for your reference. The details are as follows:

This code gets the user's age based on the date of birth, with the born parameter of type date


def calculate_age(born):
 today = date.today()
 try:
  birthday = born.replace(year=today.year)
 except ValueError:
# raised when birth date is February 29 
# and the current year is not a leap year
  birthday = born.replace(year=today.year, day=born.day-1)
 if birthday > today:
  return today.year - born.year - 1
 else:
  return today.year - born.year

I hope this article has helped you with your Python programming.


Related articles: