当前位置: 移动技术网 > IT编程>脚本编程>Python > 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

2019年07月20日  | 移动技术网IT编程  | 我要评论

星光大道云飞的妻子,潜行狙击演员名单,顶级浪荡狂徒

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

import time
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显示

import time
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'))

执行结果:

  

方法二:修改语言符号

import time,locale
timestr="2020-10-10 10:10:10"
t=time.strptime(timestr,"%y-%m-%d %h:%m:%s")
locale.setlocale(locale.lc_ctype,'chinese')
print(time.strftime("%y年%m月%d日 %h时%m分%s秒",t))

执行结果:

  

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

def change_time(timestr:str,t_int=false)->str:
    import re
    t_text = ['年', '月', '日 ', '时', '分', '秒']
    re_t = re.compile("[\d|\.]+")
    str_time = ''
    for k, v in zip(t_text, re_t.findall(timestr)):
        if t_int and '.' in v :
            v=re.sub('\.\d+', '', v)
        str_time += str(v) + k
    return str_time

if __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)

执行结果:

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网