我该如何更正此错误:时间数据“9121991”与格式“%d %m %Y”不匹配?

How can I correct this : time data '9121991' does not match format '%d %m %Y' error?

我正在尝试使用 python 从输入的出生日期计算一个人的年龄。

我已经试过 and this 但没有找到答案。

我做了以下事情:

Import datetime, date

from datetime import datetime, date

Create the following notation:

print ('Enter your date of birth here (dd mm yyyy): ')
date_of_birth = datetime.strptime(str(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)

但是当我以这种格式输入日期时 9121991 :

我得到这个值错误。

顺便说一下,当我以这种 09121991 格式输入时,我收到了这个错误

我该如何纠正这个问题?

由于您的格式中有空格,因此无法识别您的字符串。

有效:

from datetime import datetime, date

date_of_birth = datetime.strptime("09121991", '%d%m%Y')

注意不能用input输入09121991因为在Python2:

  • input 计算表达式
  • 09121991 被视为八进制数,但无效,因为它包含 9

所以替代方案是使用 raw_input()。那行得通。

顺便说一句:如果您需要用零填充,请使用 raw_input().zfill(8)。无需使用该技巧添加前导零。