我想获取 python 中的用户出生日期

I want to get the user date of birth in python

bdate = input("Type your Date of birth (ie.10/11/2011) : ")
print(bdate)
day, month, year = map(int, bdate.split('/'))
birth_date = datetime.date(day, month, year)
print(birth_date)
today = datetime.datetime.now().strftime("%Y")
print(today)
age = today - birth_date.year ```

错误:日期超出月份范围如何解决此错误

试试这个,使用 relativedelta

from dateutil.relativedelta import relativedelta
from datetime import datetime

bdate = input("Type your Date of birth (ie.10/11/2011) : ")

# convert the input string to datetime-object.
birth_date = datetime.strptime(bdate, "%d/%m/%Y")

print(f"{relativedelta(datetime.now(), birth_date).years} yrs")

如@sushanth 所说,您可以使用 relativedelta。

但为了了解您的代码有什么问题,我已经更正了它:

import datetime

bdate = input("Type your Date of birth (ie.10/11/2011) : ")

day, month, year = map(int, bdate.split('/'))
birth_date = datetime.date(year, month, day)

current_year = datetime.datetime.now().year

age = current_year - birth_date.year

print(age)

第一个问题是,datetime.date 具有以下属性: 年月日不是日月年。

第二个问题是你不能从一个整数中减去一个字符串。相反,您可以使用 datetime.datetime.now().year 获取当前年份 (int)。