2010-02-23 78 views
19

我想要一個字符串 「20091229050936」 轉換格式化時間串入 「2009年05:09 12月29日(UTC)」轉換一個字符串使用Python

>>>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'

我怎麼打算字符串轉換成一個格式化的日期字符串?

回答

10

time.strptime返回time_struct; time.strftime接受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)

40

對於datetime對象,strptimedatetime類,而不是datetime模塊中的自由功能的static method

>>> import datetime 
>>> s = datetime.datetime.strptime("20091229050936", "%Y%m%d%H%M%S") 
>>> print s.strftime('%H:%M %d %B %Y (UTC)') 
05:09 29 December 2009 (UTC) 
+1

迂腐一點:這是一個類的方法,而不是一個靜態方法。不同之處在於類方法將類本身作爲參數傳遞,因此可以爲子類動態執行;備用構造函數(如'strptime')總是(或至少應該總是)是類方法。 – ShadowRanger 2016-11-30 16:53:25

1

對我來說這是最好的,它也適用於Google App Engine

範例顯示UTC-4

import datetime 
UTC_OFFSET = 4 
local_datetime = datetime.datetime.now() 
print (local_datetime - datetime.timedelta(hours=UTC_OFFSET)).strftime("%Y-%m-%d %H:%M:%S") 
1
from datetime import datetime 
s = datetime.strptime("20091229050936", "%Y%m%d%H%M%S") 
print("{:%H:%M %d %B %Y (UTC)}".format(s)) 
1

您可以使用easy_date以方便:

import date_converter 
my_datetime = date_converter.string_to_string("20091229050936", "%Y%m%d%H%M%S", "%H:%M %d %B %Y (UTC)")