如何用python计算年龄_计算python中的年龄

很近!

您需要先将字符串转换为日期时间对象,然后才能对其进行计算 – 请参阅datetime.datetime.strptime().

对于您的日期输入,您需要执行以下操作:

datetime.strptime(input_text, "%d %m %Y")

#!/usr/bin/env python3

from datetime import datetime, date

print("Your date of birth (dd mm yyyy)")

date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")

def calculate_age(born):

today = date.today()

return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

age = calculate_age(date_of_birth)

print(age)

PS:我敦促你使用合理的输入顺序 – dd mm yyyy或ISO标准yyyy mm dd