Format time string in Python 3.3 Format time string in Python 3.3 python-3.x python-3.x

Format time string in Python 3.3


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'


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 datetimetoday = datetime.date.today()f'{today:%Y-%m-%d}'> '2018-11-01'


You can alternatively use time.strftime:

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