'{:...}'.format(mydatetime)
。lt = time.localtime(time.time())
d = datetime. datetime.fromtimestamp(time.mktime(lt))
print(userString.format(datetime=d))
英语用户可以提供'{datetime:%B %d, %Y}'
,它的格式为December 24, 2013。
中文用户可以提供'{datetime:%Y年%m月%d日}'
(使用YYYYMMDD格式,其中年表示年份,月表示月份,日表示日期)。
但是,在执行'{datetime:%Y年%m月%d日}'.format(datetime=d)
时,Python会抛出UnicodeEncodingError错误:'locale' codec can't encode character '\u5e74' in position 2: Illegal byte sequence
我知道有一个解决方法,即让我的中文用户提供类似于'{datetime:%Y}年{datime:%m}月{datetime:%d}日'
这样的格式字符串,但是不能在format_spec中显示unicode字符。如何解决这个问题?
我正在使用Windows操作系统。
谢谢
import sys; sys.getdefaultencoding()
的输出是什么? - Simeon Vissersys.getdefaultencoding()
始终为UTF-8。使用locale.getlocale()
获取当前的LC_CTYPE
类别区域设置,这是wcstombs
使用的区域设置。 - Eryk Sunlocale.getlocale(locale.LC_CTYPE)
吗?它返回(None, None)
。 - Gqqnbiglocale.setlocale(locale.LC_CTYPE, 'chinese')
之后,'{datetime:%Y年%m月%d日}'
运行良好。此外,我还可以在 format_spec 中放置日语字符。非常感谢! - Gqqnbig