擅长:python、mysql、java
<p>从Python 3.6开始,Python中的格式化可以使用<a href="https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498" rel="noreferrer">formatted string literals</a>或<em>f-strings完成:</p>
<pre><code>hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
</code></pre>
<p>或者从2.7开始的<a href="https://docs.python.org/library/stdtypes.html#str.format" rel="noreferrer">^{<cd1>}</a>函数:</p>
<pre><code>"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")
</code></pre>
<p>或者<a href="https://docs.python.org/library/stdtypes.html#printf-style-string-formatting" rel="noreferrer">string formatting ^{<cd2>} operator</a>用于更旧版本的Python,但请参见文档中的注释:</p>
<pre><code>"%02d:%02d:%02d" % (hours, minutes, seconds)
</code></pre>
<p>对于格式化时间的具体情况,有<a href="https://docs.python.org/library/time.html#time.strftime" rel="noreferrer">^{<cd3>}</a>:</p>
<pre><code>import time
t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%S %p', t)
</code></pre>