Python:如何将经过的秒数转换为H:M:S格式

Python: How to convert elapsed seconds to H:M:S format

我有这个代码:

start = time.time()

# some code here that doesn't have anything to do with the question

end = time.time()

time_result = int(end - start)

time_result 变量是完成 运行 代码所用的秒数。我如何将其转换为“00:00:00”字符串(小时、分钟和秒)?

尝试:

conversion = timedelta(seconds=time_result)
converted_time = str(conversion)
print(converted_time)

来自标准库

import datetime as dt

print(dt.datetime.fromtimestamp(time.time()))

输出

2021-08-18 14:05:44.232976

如果您只需要日期,请使用 dt.date

在这里你可以找到格式代码,docs

IIUC:将经过的秒数转换为字符串,例如 00:00:23:

import time
from datetime import datetime as dt

start = time.time()
elapsed = time.time() - start

# Edited to use UTC.
output = dt.strftime(dt.utcfromtimestamp(elapsed), '%H:%M:%S')

>>> '00:00:23'

可以在 datetime docs 中找到其他格式化字符串。