如何在 Python 的 datetime 模块中减去日期以获得年、月、日、格式的年龄



我想让这个程序了解一个人的年龄。我希望它从当前日期中减去一个人的生日。月份和日期都是正确的,但年份并不完全正确。例如,当我输入这个日期时,它会说这个人是16岁。事实上,他们应该是15岁,因为他们的16岁生日还没有到来。我该如何解决这个问题?

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)

我有一种更好的方法来表示这个代码替换

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") 

有关更多信息,您可以访问此链接

如果当前日期低于生日,则当月也会出现同样的问题。在这种情况下,你只需要为下一个更高的单元进行校正。你几乎用if语句做到了。现在,你只需要调整年份和月份。

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)

不过,还有一个问题。如果当前月份有31天,则应在当天添加31天。如果它只有30或28天,你应该加30或28。有没有一种简单的方法可以从日期时间中得到正确的数字?

您可以这样做。

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')

当你在月上加12时,你应该从年中减去1来补偿,因为1年是12个月。你今天也应该做一些类似的事情。

if month_answer < 1:
month_answer += 12
year_answer -= 1

最新更新