python - 日期时间字符串格式对齐

标签 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

这将导致:

>25 >25

代替

  2013-06-26 09:00:00       2013-06-26 09:00:00

使用字符串格式模板打印日期时间对象有什么技巧吗?

当我强制 datetime 对象进入 str() 时,它似乎起作用了

print template.format(str(l[0]), str(l[1]))

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

我是不是漏掉了一些关于字符串格式的东西,或者这对任何人来说都像是一个 python 错误?


解决方案

@mgilson 指出了我在文档中遗漏的解决方案。 link

Two conversion flags are currently supported: '!s' which calls str() on the value, and '!r' which calls repr().

Some examples:

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

最佳答案

这里的问题是 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

(在 python2.6 和 2.7 上测试)

关于python - 日期时间字符串格式对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17368438/

相关文章:

python - 使用 asyncio 同时执行两个函数

PHP:如何创建 randomDate($startDate, $endDate) 函数?

objective-c - 如何从 SQLite3 行中获取日期或日期时间?

java - 点后显示最多 X 位数字

python - 使用 python 请求的网站访问不计入谷歌分析

python - 如何将 unicode 数字转换为整数?

python 3 try-除了所有错误

php - 如何在php中分隔日期和时间?

python - 在 Python 中,%25s、%28s、%15s、%3s 等是什么意思?

string-formatting - 如何格式化 Chapel 中的字符串输出?