美文网首页
用strftime()自定义时间格式, 报错UnicodeEnc

用strftime()自定义时间格式, 报错UnicodeEnc

作者: jahonzhong | 来源:发表于2020-04-11 15:42 被阅读0次

    1、Python time strftime()方法

    描述

    Python time strftime() 函数接收以时间元组,并返回以可读字符串表示的当地时间,格式由参数format决定。

    语法

    strftime()方法语法:

    time.strftime(format[, t])

    参数

    format -- 格式字符串。

    t -- 可选的参数t是一个struct_time对象。

    2、ws['A3']=time.strftime("%Y年%m月%d日 %H时%M分%S秒",time.localtime()),当格式中存在中文字符时会报错“UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: Illegal byte sequence”

    3、解决方法:

    方法一:

    import local

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

    备注:“在Windows里,time.strftime使用C运行时的多字节字符串函数strftime,这个函数必须先根据当前locale配置来编码格式化字符串(使用PyUnicode_EncodeLocale)。”如果不设置好locale的话,根据默认的"C" locale,底层的wcstombs函数会使用latin-1编码(单字节编码)来编码格式化字符串,导致多字节编码的字符串在编码时出错。

    方法二:

    通过format函数对中文格式字符

    ws['A3']=time.strftime("%Y{Y}%m{m}%d{d} %H{H}%M{M}%S{S}",time.localtime()).format(Y='年',m='月',d='日',H='时',M='分',S='秒')

    相关文章

      网友评论

          本文标题:用strftime()自定义时间格式, 报错UnicodeEnc

          本文链接:https://www.haomeiwen.com/subject/cfnymhtx.html