python中的strptime错误“不匹配” 我的代码错误代码

问题描述


从 Python 转换日期格式时出错。

我的代码

pubDate = "Thu,08 Jul 2021 17:34:00 +0900"
pubDate = datetime.datetime.strptime(pubDate,"%a,%d %b %Y %H:%M:%s +0900")

错误代码

File "/opt/homebrew/Cellar/[email protected]/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py",line 568,in _strptime_datetime
    tt,fraction,gmtoff_fraction = _strptime(data_string,format)
File "/opt/homebrew/Cellar/[email protected]/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py",line 349,in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data 'Thu,08 Jul 2021 18:06:00 +0900' does not match format '%a,%d %b %Y %H:%M:%s +0900'

解决方法

我复制了你的代码,它运行良好,我没有收到那个错误。

pubDate = "Thu,08 Jul 2021 17:34:36 +0900"
pubDate = datetime.strptime(pubDate,"%a,%d %b %Y %H:%M:%S +0900")

pubDate
Out[6]: datetime.datetime(2021,7,8,17,34,36)

由于我的导入方式,我删除了一个 datetime,但这取决于您。 错误可能是因为 %a 取决于区域:

"因为格式取决于当前的语言环境,所以在对输出值进行假设时应该小心。字段顺序会有所不同(例如,“月/日/年”与“日/月/年”),并且输出可能包含使用区域设置的默认编码编码的 Unicode 字符(例如,如果当前区域设置是 ja_JP,则默认编码可以是 eucJP、SJIS 或 utf-8 中的任何一种;使用 locale.getlocale() 来确定当前语言环境的编码)。”

我建议检查您的语言环境以查看日期名称格式是否正确或不同。

更多信息:

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior