Gqq*_*big 7 python unicode character-encoding python-3.x
我有datetime对象,我的用户提供自己的格式字符串,以他们喜欢的方式格式化时间.
我发现的一种方法是使用'{:...}'.format(mydatetime)
.
lt = time.localtime(time.time())
d = datetime. datetime.fromtimestamp(time.mktime(lt))
print(userString.format(datetime=d))
Run Code Online (Sandbox Code Playgroud)
英语用户可以提供'{datetime:%B %d, %Y}'
格式为2013年12月24日.
中国用户可以提供'{datetime:%Y?%m?%d?}'
(YYYYMMDD格式,年=年,月=月,日=日).
但是在执行时'{datetime:%Y?%m?%d?}'.format(datetime=d)
,Python会引发UnicodeEncodingError:
'locale'编解码器无法编码位置2中的字符'\ u5e74':非法字节序列
我知道有一个解决方法,我可以告诉我的中国用户给格式字符串'{datetime:%Y}?{datime:%m}?{datetime:%d}?'
,但不能在format_spec中unicode字符显示?如何解决这个问题呢?
我正在使用Windows.
谢谢
datetime.__format__
调用datetime.strftime
,进行一些预处理然后调用time.strftime
(CPython 3.3.3源)。
在Windows上,time.strftime
使用C运行时的multibyte-string函数strftime
代替宽字符string函数wcsftime
。首先,它必须通过调用,根据当前语言环境对格式字符串进行编码PyUnicode_EncodeLocale
。依次调用CRT函数wcstombs
(MSDN),该函数将当前配置的语言环境用于LC_CTYPE
类别。如果该进程当前正在使用默认的“ C”语言环境,wcstombs
则将Latin-1(代码<256)直接转换为字节,而其他所有内容都是EILSEQ
错误,即“非法字节序列”。
使用语言环境模块来设置新的语言环境。实际的语言环境名称因平台而异,但是对于Microsoft而言,setlocale
您应该能够只设置语言字符串并使用给定语言的默认代码页。通常,对于库,您不应对此感到困惑,并且应用程序应在启动时配置语言环境。例如:
>>> import datetime, locale
>>> oldlocale = locale.setlocale(locale.LC_CTYPE, None)
>>> oldlocale
'C'
>>> newlocale = locale.setlocale(locale.LC_CTYPE, 'chinese')
>>> d = datetime.datetime.now()
>>> '{datetime:%Y\\u5e74%m\\u6708%d\\u65e5}'.format(datetime=d)
'2013\\u5e7412\\u670825\\u65e5'
Run Code Online (Sandbox Code Playgroud)
如果您希望格式化的时间使用特定于语言环境的名称(例如,月份和日期),则还可以设置LC_TIME
类别:
>>> newlocale = locale.setlocale(locale.LC_TIME, 'chinese')
>>> '{datetime:%B %d, %Y}'.format(datetime=d)
'\u5341\u4e8c\u6708 25, 2013'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
697 次 |
最近记录: |