Python3 datetime.datetime.strftime
无法接受UTF-8字符串格式。
我的操作是:
# encoding: utf-8
import datetime
f = "%Y年%m月%d日"
now = datetime.datetime.now()
print( now.strftime(f) )
我得到的是:
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
为什么会出现这个问题?我该如何解决?
f
应该是 Unicode 编码,需要在前面添加u
前缀:f = u"%Y年%m月%d日"
。此外,文件的编码头不应该是这样的,据我所知应该是这样的:# -*- coding: utf-8 -*-
。 - yedpodtrzitko