日期时间字符串格式对齐

Mar*_*son 9 python datetime string-formatting

在Python 2.7中,我想使用字符串格式的模板打印日期时间对象.由于某些原因,使用左/右对齐不能正确打印字符串.

import datetime
dt = datetime.datetime(2013, 6, 26, 9, 0)
l = [dt, dt]
template = "{0:>25} {1:>25}" # right justify
print template.format(*l)  #print items in the list using template
Run Code Online (Sandbox Code Playgroud)

这将导致:

>25 >25
Run Code Online (Sandbox Code Playgroud)

代替

  2013-06-26 09:00:00       2013-06-26 09:00:00
Run Code Online (Sandbox Code Playgroud)

是否有一些技巧使用字符串格式模板打印日期时间对象?

当我强制将datetime对象强制为str()时似乎有效

print template.format(str(l[0]), str(l[1]))
Run Code Online (Sandbox Code Playgroud)

但我宁愿不必这样做,因为我正在尝试打印一个值列表,其中一些不是字符串.制作字符串模板的重点是打印列表中的项目.

我是否遗漏了有关字符串格式的内容,或者这对任何人来说都像是一个python bug?


@mgilson指出了我在文档中遗漏的解决方案.链接

目前支持两个转换标志:'!s'在值上调用str(),'!r'调用repr().

一些例子:

"Harold's a clever {0!s}"        # Calls str() on the argument first
"Bring out the holy {name!r}"    # Calls repr() on the argument first
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 5

这里的问题是datetime对象有一个__format__方法,它基本上只是 的别名datetime.strftime。当您进行格式化时,格式化函数会传递字符串'>25',正如您所见,该字符串dt.strftime('>25')仅返回'>25'

这里的解决方法是明确使用以下命令指定字段应格式化为字符串!s

import datetime
dt = datetime.datetime(2013, 6, 26, 9, 0)
l = [dt, dt]
template = "{0!s:>25} {1!s:>25} " 
out = template.format(*l)
print out
Run Code Online (Sandbox Code Playgroud)

(在 python2.6 和 2.7 上测试)。