解决Data truncation: Incorrect datetime value: ‘2022-11-16 10:04:27‘ for column ‘created_time‘

我遇到这个问题的情况,比较少见,一般报这个错,多半是数据库的列属性与值不一致等,可以参考网上的其他文章。我这里介绍一下我这个问题的真正原因。

Python 2.7.16 (default, Mar 25 2021, 03:11:28) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = '2022-11-16 10:04:27'  #  问题字符串复制过来的
>>> a
'2022-11-16\xc2\xa010:04:27'
>>> b = '2022-11-16 10:04:27'  # 手动敲键盘
>>> b
'2022-11-16 10:04:27'

可以看到,上面a,b的输入表面上看是一样的,但输出的结果却差了很多。

a的输出值,空格部分变成了’\xc2\xa0’,这个空格是:不间断空白符 nbsp(Non-breaking space),属于 latin1 (ISO/IEC_8859-1)中的扩展字符集字符。nbsp主要用于超文本标记语言(HTML)中。

b的输出值,是正常的空字符串

>>> a.decode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 10: ordinal not in range(128)
>>> 
>>> a.decode("latin1")
u'2022-11-16\xc2\xa010:04:27'
>>> 
>>> b = '2022-11-16 10:04:27'
>>> b.decode('ascii')
u'2022-11-16 10:04:27'
>>> 
>>> b.decode("latin1")
u'2022-11-16 10:04:27'

结论是:把不间断空白符改成正常的空格就可以了。
不要小看空格,也不要随便复制,程序是一个严谨的东西,1就是1,2就是2.

猜你喜欢

转载自blog.csdn.net/dqchouyang/article/details/128561223
今日推荐