1僻弹、Python time strftime()方法
描述
Python time strftime() 函數(shù)接收以時(shí)間元組阿浓,并返回以可讀字符串表示的當(dāng)?shù)貢r(shí)間,格式由參數(shù)format決定蹋绽。
語法
strftime()方法語法:
time.strftime(format[, t])
參數(shù)
format -- 格式字符串芭毙。
t -- 可選的參數(shù)t是一個(gè)struct_time對象。
2蟋字、ws['A3']=time.strftime("%Y年%m月%d日 %H時(shí)%M分%S秒",time.localtime()),當(dāng)格式中存在中文字符時(shí)會報(bào)錯(cuò)“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運(yùn)行時(shí)的多字節(jié)字符串函數(shù)strftime,這個(gè)函數(shù)必須先根據(jù)當(dāng)前l(fā)ocale配置來編碼格式化字符串(使用PyUnicode_EncodeLocale)涂炎≈揖郏”如果不設(shè)置好locale的話设哗,根據(jù)默認(rèn)的"C" locale,底層的wcstombs函數(shù)會使用latin-1編碼(單字節(jié)編碼)來編碼格式化字符串两蟀,導(dǎo)致多字節(jié)編碼的字符串在編碼時(shí)出錯(cuò)网梢。
方法二:
通過format函數(shù)對中文格式字符
ws['A3']=time.strftime("%Y{Y}%m{m}%djhnj9nx %H{H}%M{M}%S{S}",time.localtime()).format(Y='年',m='月',d='日',H='時(shí)',M='分',S='秒')