我正在嘗試將字符串“20091229050936”轉換為“2009年12月29日(UTC)”
>>>import time >>>s = time.strptime("20091229050936", "%Y%m%d%H%M%S") >>>print s.strftime('%H:%M %d %B %Y (UTC)')
給 AttributeError: 'time.struct_time' object has no attribute 'strftime'
顯然,我犯了一個錯誤:時間錯了,它是一個日期時間對象!它有一個日期和時間組件!
>>>import datetime >>>s = datetime.strptime("20091229050936", "%Y%m%d%H%M%S")
給 AttributeError: 'module' object has no attribute 'strptime'
我是怎么意思將字符串轉換為格式化的日期字符串?
解決方案
time.strptime
返回time_struct
; time.strftime
接受a time_struct
作為可選參數:
>>>s = time.strptime(page.editTime(), "%Y%m%d%H%M%S") >>>print time.strftime('%H:%M %d %B %Y (UTC)', s)
給 05:09 29 December 2009 (UTC)
本文首發於Python黑洞網,博客園同步跟新