格式为“%”的错误指令 datetime.strptime
Bad directive in format '%' datetime.strptime
当我尝试将 str 的格式更改为日期时间时,我遇到了 ValueError,
这可能是一个简单的问题,但也无法在 google 或 Whosebug 上找到解决方案,我找到了一些关于 'z' 的解决方案是格式错误的指令,但不是 '%' 一个
current_session.date = datetime.strptime('2019-06-16 00:02', '%Y-%B-%d% %H:%M')
Traceback (most recent call last):
File "/home/rambod/PycharmProjects/mailWatcher/smtpINWatcher.py", line 92, in <module>
current_session.date = datetime.strptime('2019-06-16 00:02', '%Y-%B-%d% %H:%M')
File "/usr/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "/usr/lib/python3.7/_strptime.py", line 351, in _strptime
(bad_directive, format)) from None
ValueError: '%' is a bad directive in format '%Y-%B-%d% %H:%M'
尝试:
current_session.date = datetime.strptime('2019-06-16 00:02', '%Y-%B-%d %H:%M')
(注意删除了 d
之后多余的 %
。)
编辑:
以上仍然不正确,因为 %B
是完整的月份名称,因此您应该尝试:
current_session.date = datetime.strptime('2019-06-16 00:02', '%Y-%m-%d %H:%M')
你在%d
后面多了一个%
符号,就是这个原因。但是,您尝试解析的字符串的模式仍然是错误的 - %B
代表完整的月份名称,而不是数字。我想 %m
是你需要的:
datetime.strptime('2019-06-16 00:02', '%Y-%m-%d %H:%M')
Here's a good description on how strftime
works. Or check Python docs 更详细的解释。
%B
是 Month 作为 locale 的全名。喜欢
January, February, …, December (en_US);
Januar, Februar, …, Dezember (de_DE)
你的例子
In [25]: date = datetime.strptime('2019-06-16 00:02', '%Y-%m-%d %H:%M')
In [26]: date
Out[26]: datetime.datetime(2019, 6, 16, 0, 2)
当我尝试将 str 的格式更改为日期时间时,我遇到了 ValueError,
这可能是一个简单的问题,但也无法在 google 或 Whosebug 上找到解决方案,我找到了一些关于 'z' 的解决方案是格式错误的指令,但不是 '%' 一个
current_session.date = datetime.strptime('2019-06-16 00:02', '%Y-%B-%d% %H:%M')
Traceback (most recent call last):
File "/home/rambod/PycharmProjects/mailWatcher/smtpINWatcher.py", line 92, in <module>
current_session.date = datetime.strptime('2019-06-16 00:02', '%Y-%B-%d% %H:%M')
File "/usr/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "/usr/lib/python3.7/_strptime.py", line 351, in _strptime
(bad_directive, format)) from None
ValueError: '%' is a bad directive in format '%Y-%B-%d% %H:%M'
尝试:
current_session.date = datetime.strptime('2019-06-16 00:02', '%Y-%B-%d %H:%M')
(注意删除了 d
之后多余的 %
。)
编辑:
以上仍然不正确,因为 %B
是完整的月份名称,因此您应该尝试:
current_session.date = datetime.strptime('2019-06-16 00:02', '%Y-%m-%d %H:%M')
你在%d
后面多了一个%
符号,就是这个原因。但是,您尝试解析的字符串的模式仍然是错误的 - %B
代表完整的月份名称,而不是数字。我想 %m
是你需要的:
datetime.strptime('2019-06-16 00:02', '%Y-%m-%d %H:%M')
Here's a good description on how strftime
works. Or check Python docs 更详细的解释。
%B
是 Month 作为 locale 的全名。喜欢
January, February, …, December (en_US); Januar, Februar, …, Dezember (de_DE)
你的例子
In [25]: date = datetime.strptime('2019-06-16 00:02', '%Y-%m-%d %H:%M')
In [26]: date
Out[26]: datetime.datetime(2019, 6, 16, 0, 2)