Reputation: 309
I want this program to get a person's age. I want it to do this by subtracting a person's birthday from the current date. It gets the month and the day right but the year isn't exactly correct. For example, when I enter this date it will say that the person is 16 years of age. When in reality they should be 15 since their 16th birthday hasn't come yet. How do I fix this?
from datetime import datetime
birth = datetime(2004, 12, 25)
current = datetime.utcnow() # July 27th, 2020 at the time of writing
year_answer = current.year - birth.year
month_answer = current.month - birth.month
day_answer = current.day - birth.day
if month_answer < 1:
month_answer += 12
print(year_answer, month_answer, day_answer)
Upvotes: 0
Views: 1804
Reputation: 2227
You could do something like this.
from datetime import datetime
birth = datetime(2004, 12, 25)
current = datetime.utcnow() # July 27th, 2020 at the time of writing
year_answer = current - birth
#From here its just math
years = int(year_answer.days/365.25)
months = int((year_answer.days/30.4167)-(years*12))
days = int((year_answer.days)-(months*30.4167)-(years*12*30.4167))
print(years,'years', months,'months', days,'days','old')
Upvotes: 1
Reputation: 2894
You have got the same problem with the month if the current day is lower than the birthday. In these cases, you just have to correct for the next higher unit. You almost got there with the if-statement. Now, you just have do adjust the year and month.
from datetime import datetime
birth = datetime(2004, 12, 29)
current = datetime.utcnow() # July 27th, 2020 at the time of writing
day_answer = current.day - birth.day
month_answer = current.month - birth.month
year_answer = current.year - birth.year
if day_answer<0:
month_answer-=1
day_answer+=31
if month_answer < 0:
year_answer -=1
month_answer += 12
print(year_answer, month_answer, day_answer)
One question, though. If the current month has 31 days, you should add 31 to the day. If it only has 30 or 28 days, you should add 30 or 28. Is there an easy way to get the correct number from datetime?
Upvotes: 1
Reputation: 308111
When you add 12 to the months, you should subtract 1 from the year to compensate since 1 year is 12 months. You should do something similar for the day too.
if month_answer < 1:
month_answer += 12
year_answer -= 1
Upvotes: 0
Reputation: 9
from datetime import date
def calculateAge(birthDate):
today = date.today()
age = today.year - birthDate.year - ((today.month, today.day) < (birthDate.month, birthDate.day))
return age
print(calculateAge(date(1997, 1, 8)), "years")
Upvotes: 1