Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将datetime对象传递给str.format()时出现意外结果_Python_Datetime - Fatal编程技术网

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

Python 将datetime对象传递给str.format()时出现意外结果,python,datetime,Python,Datetime,在Python2.7中,str.format()接受非字符串参数,并在格式化输出之前调用值的\uuu\uuu方法: 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

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

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
对象传递给
str.format()
会引发
TypeError
或format
str(datetime.time)
,而返回格式化指令。为什么会这样?

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}'

“{0:你没有回答我的问题;因此必须在其他地方投票;-)
'{0:%H:%M}'
In [26]: time(10, 10).__format__(' <5')
Out[26]: ' <5'
In [29]: time(10, 10).strftime(' <5')
Out[29]: ' <5'
In [30]: '{0!s: <5}'.format(time(10, 10))
Out[30]: '10:10:00'