类似这个时间数据 '01–MAY-21' 的 strptime 错误与格式 '%d-%b-%y' 不匹配

strptime error like this time data '01–MAY-21' does not match format '%d-%b-%y'

我尝试这样的代码,它发生错误。 我不知道下面哪部分是错误代码? 我不能将代码用作下面的第一个示例。我做错了什么?

from datetime import datetime

required_format="%d-%b-%y"
a="02–MAY-21"

print(a)

aaa = datetime.strptime(a, required_format)
print(aaa)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-91-aea82823c657> in <module>
      7 
      8 
----> 9 x_date = datetime.strptime(str_date, datetime_format)
     10 print(x_date)

D:\ProgramData\Anaconda3\envs\mybase\lib\_strptime.py in _strptime_datetime(cls, data_string, format)
    566     """Return a class cls instance based on the input string and the
    567     format string."""
--> 568     tt, fraction, gmtoff_fraction = _strptime(data_string, format)
    569     tzname, gmtoff = tt[-2:]
    570     args = tt[:6] + (fraction,)

D:\ProgramData\Anaconda3\envs\mybase\lib\_strptime.py in _strptime(data_string, format)
    347     found = format_regex.match(data_string)
    348     if not found:
--> 349         raise ValueError("time data %r does not match format %r" %
    350                          (data_string, format))
    351     if len(data_string) != found.end():

ValueError: time data '02–MAY-21' does not match format '%d-%b-%y'

同时,我尝试使用 unable to solve strptime() issue even after trying all the formats

中的代码
from datetime import datetime

required_format="%d-%b-%y"
a = "02-MAY-21"
frmt = datetime.strptime(a, required_format)
print(frmt)

效果很好,这是结果 2021-05-02 00:00:00

我认为两者几乎相同,代码中几乎没有不同的部分,但这并不重要。

您的原始字符串以 U+2013 EN DASH 字符作为分隔符:

>>> x ='02–MAY-21'
>>> hex(ord(x[2]))
8211

您尝试的格式字符串有规则的破折号 (U+002D)。

>>> f = '%d-%b-%y'
>>> hex(ord(f[2]))
'0x2d'

您可能希望将短划线规范化为常规破折号,并使用带有常规破折号的格式模式。

>>> datetime.strptime(x.replace("\u2013", "-"), "%d-%b-%y")
datetime.datetime(2021, 5, 2, 0, 0)
>>>