Age from birthdate in python
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Question
00:23 Accepted answer (Score 408)
00:45 Answer 2 (Score 70)
01:07 Answer 3 (Score 21)
01:26 Answer 4 (Score 20)
01:47 Thank you
--
Full question
https://stackoverflow.com/questions/2217...
Answer 1 links:
[Danny's solution]: https://stackoverflow.com/a/9754466/6538...
Answer 3 links:
[python-dateutil]: http://labix.org/python-dateutil
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Question
00:23 Accepted answer (Score 408)
00:45 Answer 2 (Score 70)
01:07 Answer 3 (Score 21)
01:26 Answer 4 (Score 20)
01:47 Thank you
--
Full question
https://stackoverflow.com/questions/2217...
Answer 1 links:
[Danny's solution]: https://stackoverflow.com/a/9754466/6538...
Answer 3 links:
[python-dateutil]: http://labix.org/python-dateutil
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 433
That can be done much simpler considering that int(True) is 1 and int(False) is 0, and tuples comparison goes from left to right:
from datetime import date
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
ANSWER 2
Score 70
from datetime import 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, month=born.month+1, day=1)
if birthday > today:
return today.year - born.year - 1
else:
return today.year - born.year
Update: Use Danny's solution, it's better
ANSWER 3
Score 21
from datetime import date
days_in_year = 365.2425
age = int((date.today() - birth_date).days / days_in_year)
In Python 3, you could perform division on datetime.timedelta:
from datetime import date, timedelta
age = (date.today() - birth_date) // timedelta(days=365.2425)
ANSWER 4
Score 12
The simplest way is using python-dateutil
import datetime
import dateutil
def birthday(date):
# Get the current date
now = datetime.datetime.utcnow()
now = now.date()
# Get the difference between the current date and the birthday
age = dateutil.relativedelta.relativedelta(now, date)
age = age.years
return age