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 報錯:

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)

執行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM