我想在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 ```

错误:天超出了月份的范围如何解决此错误

就像@susshanth说你可以使用relativelta。

但为了理解你的代码出了什么问题,我已经纠正了它:

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((.eyear来获取当前年份(int(。

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

相关内容

最新更新