Python 3.8 在Python中如何减去日期时间?

Python 3.8 在Python中如何减去日期时间?,python-3.8,Python 3.8,我正在尝试为python制作一个年龄计算器,但在减去用户输入的出生日期和今天的日期时遇到了一个问题。我试过浮动,但不起作用。我试着减去变量本身,但也不起作用 age_str = input ("Enter your birthday on dd-mm-yy Format:")``` age = datetime.datetime.strptime(age_str, '%d-%m-%Y')``` today_str = datetime.date.today()``` today = dat

我正在尝试为python制作一个年龄计算器,但在减去用户输入的出生日期和今天的日期时遇到了一个问题。我试过浮动,但不起作用。我试着减去变量本身,但也不起作用

age_str = input ("Enter your birthday on dd-mm-yy Format:")```

age = datetime.datetime.strptime(age_str, '%d-%m-%Y')```

today_str = datetime.date.today()```

today = datetime.datetime.strptime(today_str, '%d-%m-%Y')```

total = age - today```
from datetime导入日期
def计算年龄(出生):
今天=日期。今天()
返回今日.year-born.year-((今日.month,今日.day)<(今日.month,今日.day))

如果您报告失败的代码,最好发布错误消息。我认为您的年龄变量实际上应该是生日变量,因为您通过减去
age=today-birth
来确定年龄,当然也可以使用减法的绝对值。也许这篇文章会有所帮助。虽然此代码可能会回答该问题,但提供有关此代码为什么和/或如何回答该问题的附加上下文可提高其长期价值。
from datetime import date

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))