36

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

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

However I get the error:

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

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

falsetru
  • 357,413
  • 63
  • 732
  • 636
markmnl
  • 11,116
  • 8
  • 73
  • 109

3 Answers3

47

time.localtime returns time.struct_time which does not support strftime-like formatting.

Pass datetime.datetime object which support 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'
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • is there any downside to using datetime.datetime instead of time? – markmnl Feb 07 '14 at 02:55
  • 1
    OK, I see there differences here: http://stackoverflow.com/questions/7479777/difference-between-datetime-vs-time-modules, datetime is more suited to my needs, thanks! – markmnl Feb 07 '14 at 02:57
  • Try this too: f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S}" – Kieveli Dec 20 '19 at 19:26
  • @Kieveli, The question is tagged `python-3.3`. f-string syntax is available in Python 3.6+. [Another answer](https://stackoverflow.com/a/53108615/2225682) already mentioned f-string. :) – falsetru Dec 20 '19 at 22:02
28

And for newer versions of Python (3.6+, https://www.python.org/dev/peps/pep-0498/ purely for completeness), you can use the newer string formatting, ie.

import datetime

today = datetime.date.today()

f'{today:%Y-%m-%d}'
> '2018-11-01'
seaders
  • 3,878
  • 3
  • 40
  • 64
25

You can alternatively use time.strftime:

time.strftime('{%Y-%m-%d %H:%M:%S}')
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
sashkello
  • 17,306
  • 24
  • 81
  • 109