程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(1)

2023-06(2)

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

发布于2019-08-06 10:55     阅读(1221)     评论(0)     点赞(5)     收藏(2)


使用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)

执行结果:

 



所属网站分类: 技术文章 > 博客

作者:heer

链接:https://www.pythonheidong.com/blog/article/7978/d888c8f20465f13753b9/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

5 0
收藏该文
已收藏

评论内容:(最多支持255个字符)