有没有办法将 timedelta 对象格式化为小时-分钟-seconds.MILLISECONDS?

Is there a way to format a timedelta object to be hours-minutes-seconds.MILLISECONDS?

我有这样的东西:

import datetime

a = datetime.datetime.now()
do_something_for_a_long_time()
b = datetime.datetime.now()
c = b - a

print("Doing <something> took {c}".format(c))

问题是这很好用,但我们希望秒值的形式为 .,而不是微秒?

我能够从那个 timedelta 对象中分离出毫秒属性,它似乎只有微秒可用。

如果你不想手动四舍五入,就去掉微秒的最后三位数字:

def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
return s[:-3] `def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
return s[:-3]

鉴于您的初始代码示例,您可以使用如下内容:

# 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}")

这导致

# c = datetime.timedelta(seconds=7, microseconds=319673)
Doing <something> took 0:00:07.320

看看 Python 的内置函数 round() and divmod() and please poke around this and this related thread; also, please read through this and this thread to learn more about formatting timedelta 对象。