I have datetime object and my users provide their own format string to format the time in the way they like.
One way I find is to use '{:...}'.format(mydatetime).
lt = time.localtime(time.time()) d = datetime. datetime.fromtimestamp(time.mktime(lt)) print(userString.format(datetime=d)) English users may provide '{datetime:%B %d, %Y}', which formats to December 24, 2013.
Chinese users may provide '{datetime:%Y年%m月%d日}' (in YYYYMMDD format, 年=Year, 月=Month, 日=Day).
But when executing '{datetime:%Y年%m月%d日}'.format(datetime=d), Python raises UnicodeEncodingError: 'locale' codec can't encode character '\u5e74' in position 2: Illegal byte sequence
I know there is a workaround that I can tell my Chinese users to give format string like '{datetime:%Y}年{datime:%m}月{datetime:%d}日', but cannot unicode character show in format_spec? How to solve this problem?
I'm using Windows.
Thanks
import sys; sys.getdefaultencoding()?sys.getdefaultencoding()is always UTF-8. Uselocale.getlocale()to get the current locale for theLC_CTYPEcategory, which is whatwcstombsuses.locale.getlocale(locale.LC_CTYPE)? It returns(None, None).locale.setlocale(locale.LC_CTYPE, 'chinese'),'{datetime:%Y年%m月%d日}'runs well. Besides, I can also put Japanese characters in format_spec. Thank you so much!