2014-02-07 52 views
8

我想獲取當前的當地時間格式爲字符串:year-month-day hour:mins:seconds。我將用於記錄。在Python 3.3格式化時間字符串3.3

import time 
'{0:%Y-%m-%d %H:%M:%S}'.format(time.localtime()) 

但是我得到的錯誤:

 
Traceback (most recent call last): 
File "", line 1, in 
ValueError: Invalid format specifier 

我在做什麼錯了我的文檔閱讀中,我可以做到這一點?有沒有更好的辦法?

回答

15

time.localtime返回time.struct_time它不支持類似strftime的格式。

通過datetime.datetime支持strftime格式化的對象。 (見datetime.datetime.__format__

>>> import datetime 
>>> '{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()) 
'2014-02-07 11:52:21' 
+0

沒有任何缺點使用datetime.datetime而不是時間? – markmnl

+0

好的,我在這裏看到有不同:http://stackoverflow.com/questions/7479777/difference-between-datetime-vs-time-modules,datetime更適合我的需求,謝謝! – markmnl

6

您也可以使用time.strftime

time.strftime('{%Y-%m-%d %H:%M:%S}') 
+1

我很確定'0:'對於'strftime'是多餘的。 +1 –