Python显示中文时间编码问题解决

方法一:

import locale
import datetime

locale.setlocale(locale.LC_CTYPE, 'chinese')

times = datetime.datetime.now()
print(times.strftime('%Y年%m月%d日'))
效果:2020年04月30日

默认用的"C语言 locale,底层的wcstombs函数会使用latin-1编码(单字节编码)来编码格式化字符串,单字节转多字节编码时报错。
在Windows里,time.strftime使用C运行时的多字节字符串函数strftime


方法二:

import locale
import datetime

locale.setlocale(locale.LC_CTYPE, 'chinese')

times = datetime.datetime.now()
print(times.strftime(f'%Y{"年"}%m{"月"}%d{"日"}'))   #也可以使用format进行传参
效果:2020年04月30日

参考:https://blog.csdn.net/imnisen1992/article/details/53333212

原文地址:https://www.cnblogs.com/remixnameless/p/12810929.html