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

Sree Durkesh:
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 ```

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

devj3ns:

就像@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)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章