0

I want to calculate age. I am going to receive the birthday from user and calculate the age. I think I need to convert the Input type into date format. Can someone helps me?

I tried to make a list of [year, month, day]. They are integers and I used the following formula to calculate the age but I ran into the error(int type in callable).

Age=(Now.year-Birthday[0])-(Now.month,Now.day)<(Birthday[1],Birthday[2])
  • Does this answer your question? [Age from birthdate in python](https://stackoverflow.com/questions/2217488/age-from-birthdate-in-python) – FObersteiner Mar 29 '21 at 13:39
  • You can construct a [`datetime.date`](https://docs.python.org/3/library/datetime.html#datetime.date) from 3 integers, which means you will need to first convert the 3 strings into integers (by calling [`int()`](https://docs.python.org/3/library/functions.html#int)). – martineau Mar 29 '21 at 13:45
  • @MrFuppes I studied those answers before. The problem is all of them are not going to get birthday from user. For example my code gets it, split it and make all the Y,M,D integers, but i don't know what is the problem with the formula, because everything is integers. – Mohammadreza Shahsavar Mar 29 '21 at 13:47
  • @martineau my code gets input it, split it and make all the Y,M,D integers, but i don't know what is the problem with the formula, because everything is integers. – Mohammadreza Shahsavar Mar 29 '21 at 13:48
  • 1
    Once you have two dates, you can subtract them yielding a [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta). You should be able to calculate the age from that. – martineau Mar 29 '21 at 13:53
  • Also see [Difference between now and birthdate in years, months, days, mintues](https://stackoverflow.com/questions/44917134/difference-between-now-and-birthdate-in-years-months-days-mintues). – martineau Mar 29 '21 at 14:09

1 Answers1

1

By importing datetime class (from datetime module, they're called the same, it's confusing) you can use the strptime() to translate dates from string to Date:

from datetime import datetime
import math

bday_str = '18/04/1998'
bday_date = datetime.strptime(bday_str, '%d/%m/%y')

This would get you '18/04/1998' as a Date object, which later on you can use to operate to get the age of the person:

now = datetime.datetime.now()
age = math.trunc((now-bday_date).days/365.2425)
print(age)
>>> 22
Roger
  • 158
  • 8