使用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黑洞網,博客園同步跟新


免責聲明!

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



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