2

I want to convert milliseconds and have 2:00 output. It should look like duration of the song.

I was trying with this code:

import datetime

seconds = milliseconds/1000
b = int((seconds % 3600)//60)
c = int((seconds % 3600) % 60)
dt = datetime.time(b, c)
print(dt)

>>> 02:30:00

Do you have another ideas? Or maybe I should change something in my code.

Edit: I solved the problem with following code

    ms = 194000
    seconds, ms = divmod(ms, 1000)
    minutes, seconds = divmod(seconds, 60)
    print(f'{int(minutes):01d}:{int(seconds):02d}')
Wiktor_B
  • 395
  • 1
  • 4
  • 8
  • Do you care about leftover fractions of a second? You might be looking for the `divmod` function, which combines `//` and `%` into a single step: `divmod(130, 60) == (2, 10)`. – chepner May 07 '21 at 15:59

4 Answers4

3
>>> import datetime
>>> print(datetime.timedelta(milliseconds=3200))
0:00:03.200000
Woodford
  • 3,746
  • 1
  • 15
  • 29
  • 1
    This is probably the most sensible choice, but doesn't show how to format it! – ti7 May 07 '21 at 16:10
3

What about using a simple divmod? That way, minutes > 59 are possible and no imports needed, e.g.

milliseconds = 86400001 # a day and a millisecond... long song.

seconds, milliseconds = divmod(milliseconds, 1000)
minutes, seconds = divmod(seconds, 60)

print(f'{int(minutes):02d}:{int(seconds):02d}.{int(milliseconds):03d}')
# 1440:00.001
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
2

b is minutes and c is seconds. But the arguments to datetime.time() are hours, minutes, seconds. So you're putting the minutes in the hours parameter, and seconds in the minutes parameter.

Use

dt = datetime.time(0, b, c)
print(dt)
>>> 00:02:30

If you don't want the initial 00:, use

print(dt.strftime('%M:%S'))
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Ah - that gets the other half - realistically, they should specify the arguments `.time(minutes=foo, seconds=bar)` during creation! [class signature](https://docs.python.org/3/library/datetime.html#datetime.time) – ti7 May 07 '21 at 16:07
0

If you're using datetime, you're looking for the .strftime() method!

"%M:%S"  # minutes:seconds

You can find a table of format codes here: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

However, it's probably easier to just do the math yourself

>>> milliseconds  = 105000
>>> total_seconds = int(milliseconds / 1000)
>>> minutes       = int(total_seconds / 60)
>>> seconds       = int(total_seconds - minutes * 60)
>>> print("{}:{:02}".format(minutes, seconds))
1:45
ti7
  • 16,375
  • 6
  • 40
  • 68