简体   繁体   中英

Python: TimeDelta how to show only minutes and seconds

I have the following code:

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

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

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

This is the output:

0:01:03.681325

And this is the output i am looking to achieve:

1:03

If you rely on just the default string representation of a timedelta object, you will get that format. Instead, you will have to specify your own formatting:

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))

And with this you get this output:

1:03

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM