Python:TimeDelta如何只显示分钟和秒

icomxhvb  于 2023-02-18  发布在  Python
关注(0)|答案(3)|浏览(268)

下面的代码:

if (len(circles[0, :])) == 5:
            start = time.time()

        if (len(circles[0, :])) == 1:
            end = time.time()

            print(str(timedelta(seconds=end-start)))

以下是输出:

0:01:03.681325

这就是我希望达到的结果:

1:03
sulc1iza

sulc1iza1#

如果只依赖timedelta对象的默认字符串表示,则会得到该格式。相反,您必须指定自己的格式:

from datetime import timedelta

def convert_delta(dlt: timedelta) -> str:
    minutes, seconds = divmod(int(dlt.total_seconds()), 60)
    return f"{minutes}:{seconds:02}"

# this is your time from your code
dlt = timedelta(minutes=1, seconds=3, milliseconds=681.325)

print(convert_delta(dlt))

这样你就得到了这个输出:

1:03
k7fdbhmy

k7fdbhmy2#

根据wkl的回答,你可以用int(input())输入分、秒,用float(input())输入毫秒。

nwsw7zdq

nwsw7zdq3#

简单地打印字符串的一个切片怎么样?例如:

# Convert timedelta to string:
td_str = str(timedelta(seconds=end-start))

# Starting index of slice is the position of the first number in td_str that isn't '0':
starting_numbers = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}
for character_index, character in enumerate(td_str):
    if character in starting_numbers:
        start_slice_index = character_index
        break

# End of slice is always '.':
end_slice_index = td_str.index(".")

# Make sure that time still displays as '0:xx' when time goes below one minute:
if end_slice_index - start_slice_index <= 3:
    start_slice_index = end_slice_index - 4

# Print slice of td_str:    
print(f'{td_str[start_slice_index:end_slice_index]}')

此解决方案的优点是,如果时间超过一个小时,打印的时间仍然正确显示。

相关问题