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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章