tru*_*com 4 python unicode python-3.x
python3 datetime.datetime.strftime无法接受utf-8字符串格式
我做的是::
# encoding: utf-8
import datetime
f = "%Y?%m?%d?"
now = datetime.datetime.now()
print( now.strftime(f) )
Run Code Online (Sandbox Code Playgroud)
而我得到的是:
D:\pytools>python a.py
Traceback (most recent call last):
File "a.py", line 6, in <module>
print( now.strftime(f) )
UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2
: Illegal byte sequence
Run Code Online (Sandbox Code Playgroud)
为什么以及如何解决这个问题?
问题不在于datetime,它在print.请参阅PrintFails
啊,这不完全是 - 虽然它有相同的原因,你很可能有问题将Unicode写入stdout.(使用带有Python shell的IDE,例如最新的IDLE,可以避免这种情况.)
最终调用的strftime()函数是datetime.strftime()C标准库的一部分,它在Windows/MSVCRT下无法处理Unicode字符串.(虽然理论上你可以通过将代码页设置为65001并使用UTF-8来解决它,但是在该代码页的C运行时中存在严重的长期错误.)
Python中的解决方法可能是在调用之后替换非ASCII字符:
strftime('%Y{0}%m{1}%d{2}').format(*'???')
Run Code Online (Sandbox Code Playgroud)
或者避免strftime自己做.
这可能被认为是一种错误,time.strftime()并通过这些方法中的任何一种进行修复.添加Python本机实现是有意义的strftime- strptime由于该函数中的其他平台错误,它们已经必须执行相同的操作.
>>> now.strftime(\'%Y\xe5\xb9\xb4%m\xe6\x9c\x88%d\xe6\x97\xa5 %H\xe6\x97\xb6%M\xe5\x88\x86%S\xe7\xa7\x92\'.encode(\'unicode- \n escape\').decode()).encode().decode("unicode-escape")\n\n\'2018\xe5\xb9\xb404\xe6\x9c\x8812\xe6\x97\xa5 15\xe6\x97\xb655\xe5\x88\x8632\xe7\xa7\x92\'\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
3169 次 |
| 最近记录: |