1. 程式人生 > 程式設計 >使用Python將字串轉換為格式化的日期時間字串

使用Python將字串轉換為格式化的日期時間字串

我正在嘗試將字串“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將字串轉換為格式化的日期時間字串,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回覆大家的!