Format time string in Python 3.3

I am trying to get the current local time as a string in the format: year-month-day hour: mins: seconds. What I will use for logging. In my reading of the documentation, I can do this:

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

However, I get an error message:

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

What am I doing wrong? Is there a better way?

+8
python datetime
source share
2 answers

time.struct_time returns time.struct_time , which does not support strftime-style formatting.

Pass datetime.datetime object that supports strftime formatting. (See datetime.datetime.__format__ )

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

Alternatively, you can use time.strftime :

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

All Articles