Home > Enterprise >  Python: TimeDelta how to show only minutes and seconds
Python: TimeDelta how to show only minutes and seconds

Time:07-17

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

CodePudding user response:

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

CodePudding user response:

Based on wkl's answer, you could input the minutes, seconds, using int(input()) and milliseconds using float(input()).

  • Related