-3

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
Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
Ethan0619
  • 25
  • 1
  • 6

3 Answers3

1

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
  • 77,184
  • 16
  • 165
  • 176
  • Unfortunately this will not work as i am using live data for this program.. i cannot input the time into the code as it changes every time – Ethan0619 Jul 16 '22 at 22:20
  • 1
    @Ethan0619 This was just an example of how to do the calculation, with a minimum code sample. I just converted the code to make the conversion a method. You can put the `convert_delta` method into your code and call it with your deltas and print the result. – wkl Jul 16 '22 at 22:20
0

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

0

How about simply printing a slice of the string? For example:

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

The advantage of this solution would be that if the time happens to go over one hour, the printed time still displays correctly.

Jan van Wijk
  • 101
  • 1
  • 4