1 问题
import time
# 将时间字符串转换成时间元组
struct_time = time.strptime('20200910', "%Y%m%d")
print('时间元组', struct_time)
# 将时间元组转换成格式化的时间字符串
format_time = time.strftime("%Y年%m月%d日", struct_time)
print(format_time)
报错:
Traceback (most recent call last):
File "D:/workspace/PycharmProjects/Problems/DateUnicodeError.py", line 5, in <module>
format_time = time.strftime("%Y年%m月%d日", struct_time)
UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: Illegal byte sequence
2 解决方案
# format_time = time.strftime("%Y年%m月%d日", struct_time)
format_time = time.strftime("%Y{y}%m{m}%d{d}", struct_time).format(y='年', m='月', d='日')
输出结果:
时间元组 time.struct_time(tm_year=2020, tm_mon=9, tm_mday=10, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=254, tm_isdst=-1)
2020年09月10日