Format time string in Python 3.3

故事扮演 提交于 2020-04-29 10:26:26

问题


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?


回答1:


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'



回答2:


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'



回答3:


You can alternatively use time.strftime:

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


来源:https://stackoverflow.com/questions/21618351/format-time-string-in-python-3-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!