python encoding报错_python中time.strftime不支持中文,报错UnicodeEncodeError: 'locale' codec can't encode charac...

python中time.strftime不支持中文,报错UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: encoding error

时间:2019-07-20

本文章向大家介绍python中time.strftime不支持中文,报错UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: encoding error,主要包括python中time.strftime不支持中文,报错UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: encoding error使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用time.strftime将 "2020-10-10 10:10:10" 转化为  2020年10月10日10时10分10 报错:

importtime

timestr="2020-10-10 10:10:10"t=time.strptime(timestr,"%Y-%m-%d %H:%M:%S")print(time.strftime("%Y年%m月%d日 %H时%M分%S秒",t))

根据错误可以看出,没有执行成功的原因是"%Y年%m月%d日 %H时%M分%S秒"中包含了中文,中文没有转化为unicode编码失败的。

解决方法:

方法一:先转为uncode编码执行,执行完后转为utf-8显示

importtime

timestr="2020-10-10 10:10:10"t=time.strptime(timestr,"%Y-%m-%d %H:%M:%S")print(time.strftime("%Y年%m月%d日 %H时%M分%S秒".encode('unicode_escape').decode('utf8'),t).encode('utf-8').decode('unicode_escape'))

执行结果:

方法二:重写一个自定义转化函数

def change_time(timeStr:str,t_int=False)->str:importre

t_text= ['年', '月', '日', '时', '分', '秒']

re_t= re.compile("[\d|\.]+")

str_time= ''

for k, v inzip(t_text, re_t.findall(timeStr)):if t_int and '.' inv :

v=re.sub('\.\d+', '', v)

str_time+= str(v) +kreturnstr_timeif __name__ == '__main__':print(datetime.now())

t=change_time(str(datetime.now()))

int_t=change_time(t,True)

float_t=change_time(t)print(int_t)print(float_t)

执行结果:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值