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}')
1
  • 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). Commented May 7, 2021 at 15:59

4 Answers 4

6

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
Sign up to request clarification or add additional context in comments.

Comments

4
>>> import datetime
>>> print(datetime.timedelta(milliseconds=3200))
0:00:03.200000

1 Comment

This is probably the most sensible choice, but doesn't show how to format it!
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'))

1 Comment

Ah - that gets the other half - realistically, they should specify the arguments .time(minutes=foo, seconds=bar) during creation! class signature
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.