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

问题描述 投票:0回答:4

我有以下代码:

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
python time format string-formatting
4个回答
1
投票

如果您仅依赖

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

0
投票

根据wkl的答案,您可以使用

int(input())
输入分钟、秒,使用
float(input())
输入毫秒。


0
投票

简单地打印字符串的一部分怎么样?例如:

# 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(td_str[start_slice_index:end_slice_index])

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


0
投票

这就是你所要做的!

import time
from datetime import timedelta


start = time.time()
time.sleep(3.681325)
end = time.time()

print(str(timedelta(seconds=end - start)).split('.')[0])

© www.soinside.com 2019 - 2024. All rights reserved.