将datetime对象传递给str.format()时出现意外结果

时间:2016-01-04 10:59:27

标签: python datetime

在Python 2.7中,str.format()接受非字符串参数,并在格式化输出之前调用值的__str__方法:

class Test:
     def __str__(self):
         return 'test'

t = Test()
str(t) # output: 'test'
repr(t) # output: '__main__.Test instance at 0x...'

'{0: <5}'.format(t) # output: 'test ' in python 2.7 and TypeError in python3
'{0: <5}'.format('a') # output: 'a    '
'{0: <5}'.format(None) # output: 'None ' in python 2.7 and TypeError in python3
'{0: <5}'.format([]) # output: '[]   ' in python 2.7 and TypeError in python3

但是当我传递一个datetime.time对象时,我在Python 2.7和Python 3中得到' <5'作为输出:

from datetime import time
'{0: <5}'.format(time(10,10)) # output: ' <5'

datetime.time对象传递给str.format()应该引发TypeError或格式str(datetime.time),而是返回格式化指令。那是为什么?

2 个答案:

答案 0 :(得分:10)

'{0: <5}'.format(time(10, 10))会调用time(10, 10).__format__,该<5会为<5格式说明符返回In [26]: time(10, 10).__format__(' <5') Out[26]: ' <5'

time_instance

这是因为time_instance.__format__尝试使用time.strftime格式化time.strftime,而In [29]: time(10, 10).strftime(' <5') Out[29]: ' <5' 并不了解格式化指令。

!s

str.format转换标记会告诉str在呈现结果之前调用time实例上的str(time(10, 10)).__format__(' <5') - 它会调用In [30]: '{0!s: <5}'.format(time(10, 10)) Out[30]: '10:10:00'

{{1}}

答案 1 :(得分:2)

格式化时,

datetime个对象支持datetime.strftime()选项:

>>> from datetime import time
>>> '{0:%H}'.format(time(10,10))
'10'

该格式包括对文字文本的支持:

>>> time(10, 10).strftime('Hour: %H')
'Hour: 10'

>5格式被视为文字文字。您可以使用以下格式将时间安排到5个字符的列中:

'{0:%H:%M}'