在Python 3.3中格式化时间字符串 [英] Format time string in Python 3.3

查看:150
本文介绍了在Python 3.3中格式化时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以字符串形式获取当前本地时间,格式为:年-月-日小时:分钟:秒。我将使用它进行日志记录。通过阅读文档,我可以通过以下方式做到这一点:

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())

但是我得到了错误:


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

我在做什么错?有更好的方法吗?

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

推荐答案

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

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

通过 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'

这篇关于在Python 3.3中格式化时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆