2014-02-07 32 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 –