在 Python 3.3 中格式化时间字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21618351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:16:22  来源:igfitidea点击:

Format time string in Python 3.3

pythonpython-3.xdatetimepython-3.3

提问by markmnl

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?

我究竟做错了什么?有没有更好的办法?

采纳答案by falsetru

time.localtimereturns time.struct_timewhich does not support strftime-like formatting.

time.localtime返回time.struct_time不支持类似 strftime 的格式。

Pass datetime.datetimeobject which support strftime formatting. (See datetime.datetime.__format__)

传递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'

回答by sashkello

You can alternatively use time.strftime:

您也可以使用time.strftime

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

回答by seaders

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.

对于较新版本的 Python(3.6+,https://www.python.org/dev/peps/pep-0498/纯粹是为了完整性),您可以使用较新的字符串格式,即。

import datetime

today = datetime.date.today()

f'{today:%Y-%m-%d}'
> '2018-11-01'