<p>给出初始代码示例,您可以使用如下内容:</p>
<pre class="lang-py prettyprint-override"><code># From your example.
c = b - a
# Get the hours, minutes, and seconds.
minutes, seconds = divmod(c.seconds, 60)
hours, minutes = divmod(minutes, 60)
# Round the microseconds to millis.
millis = round(c.microseconds/1000, 0)
print(f"Doing <something> took {hours}:{minutes:02}:{seconds:02}.{millis}")
</code></pre>
<p>导致</p>
<pre><code># c = datetime.timedelta(seconds=7, microseconds=319673)
Doing <something> took 0:00:07.320
</code></pre>
<p>看看Python的内置函数<a href="https://docs.python.org/3/library/functions.html#round" rel="nofollow noreferrer">round()</a>和<a href="https://docs.python.org/3/library/functions.html#divmod" rel="nofollow noreferrer">divmod()</a>,请浏览一下与<a href="https://stackoverflow.com/questions/2119472/convert-a-timedelta-to-days-hours-and-minutes">this</a>和<a href="https://stackoverflow.com/questions/14540143/python-3-float-decimal-points-precision">this</a>相关的线程;另外,请通读<a href="https://stackoverflow.com/questions/538666/format-timedelta-to-string">this</a>和<a href="https://stackoverflow.com/questions/8906926/formatting-timedelta-objects">this</a>线程以了解有关格式化<a href="https://docs.python.org/3/library/datetime.html#timedelta-objects" rel="nofollow noreferrer">timedelta</a>对象的更多信息</p>