故障排除“ValueError:时间数据...与格式不匹配”使用 datetime.strptime 时
我的输入字符串是 '16-MAR-2010 03:37:04'
我想将其存储为日期时间。
我正在尝试使用:
db_inst.HB_Create_Ship_Date = datetime.strptime(fields[7]," %d-%b-%Y %H:%M:%S ")
fields[7] = '16-MAR-2010 03:37:04'
我收到错误:
::ValueError: time data '16-MAR-2010 03:37:04' does not match format ' %d-%b-%Y %H:%M:%S '
My input string is '16-MAR-2010 03:37:04'
and i want to store it as datetime.
I am trying to use:
db_inst.HB_Create_Ship_Date = datetime.strptime(fields[7]," %d-%b-%Y %H:%M:%S ")
fields[7] = '16-MAR-2010 03:37:04'
I am getting an error:
::ValueError: time data '16-MAR-2010 03:37:04' does not match format ' %d-%b-%Y %H:%M:%S '
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑:
正如 John 提到的,让自己更轻松并删除前导和尾随空格。
另一个想法:
您当前的区域设置可能未将“MAR”指定为月份缩写。
这段代码的输出是什么?:
我在 Linux 机器(Ubuntu 9.10,Python 2.6.4)上测试了你的代码并得到了 ValueError。
我删除了空格,更改为非英语语言环境(捷克语),并得到了 ValueError。
学术笔记:
奇怪的是,您的代码可以在 Windows XP Python 2.5.5 上运行,并带有多余的空格:
Edit:
As John mentions, make it easier on yourself and remove the leading and trailing spaces.
Another thought:
Your current locale may not specify "MAR" as a month abbreviation.
What does the output of this code give?:
I tested your code on a Linux machine (Ubuntu 9.10, Python 2.6.4) and got the ValueError.
I removed the spaces, changed to non-English locale (Czech), and got the ValueError.
Academic note:
Oddly your code works on Windows XP Python 2.5.5 with the extraneous spaces:
您的格式字符串具有前导空格和尾随空格,但您的输入字符串没有。删除起始引号后面和结束引号之前的空格。
Your format string has a leading space and a trailing space, but your input string does not. Remove the space after the starting quotation mark and before the ending quotation mark.
去掉格式前后的空格。我认为 strptime 的记录会根据为您的机器编写 C 运行时的人的突发奇想而变化。不过看来我错了。这意味着 Python 中存在错误。
Windows 上的 Python 2.6.4 不喜欢前导尾随空格;见下文。
*x 位用户,您发现了什么?
同时,使用最小的共同点——去掉空格。正如 Adam 提到的,您可能还遇到区域设置问题。
有空格:
无空格:
Lose the spaces at the front and back of your format. I thought that strptime was documented to vary depending on the whims of whoever wrote the C runtime for your box. However it seems I'm wrong. Which would mean that there's a bug in Python.
Python 2.6.4 on Windows doesn't like leading trailing spaces; see below.
*x users, what do you find?
In the meantime, use the lowest common denominator -- lose the spaces. You may also have a locale problem, as Adam mentioned.
With spaces:
Without spaces:
试试这个:
此外,查看此处作为 Python 中日期时间格式的参考。
Try this:
Also, have a look here as a reference for DateTime formatting in Python.