0

This is different from this post.

I am working on converting milliseconds to this format "{minutes}:{seconds}" in Python.

I've already implement this conversion

duration_in_ms = 350001
x = duration_in_ms / 1000
seconds = x % 60
x /= 60
'{}:{}'.format(str(int(x)).zfill(2), round(seconds,3))

the output is

'05:50.001'

is there a more efficient way to do this?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

2 Answers2

5

You could use an f-string:

duration = 350001
minutes, seconds = divmod(duration / 1000, 60)

f'{minutes:0>2.0f}:{seconds:.3f}'

Output:

'05:50.001'
gmds
  • 19,325
  • 4
  • 32
  • 58
1

There you go:

import datetime
duration_in_ms = 350001
print(datetime.datetime.fromtimestamp(duration_in_ms/1000.0).strftime('%M:%S.%f')[:-3])

Example:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

> import datetime
> duration_in_ms = 350001
> print(datetime.datetime.fromtimestamp(duration_in_ms/1000.0).strftime('%M:%S.%f')[:-3])
05:50.001
Toni Sredanović
  • 2,280
  • 1
  • 11
  • 13
  • That gave output as `35:50.001`. Is something wrong? – J...S May 24 '19 at 06:43
  • 1
    I'm getting the right output, updated my answer with example, tested it with [repl](https://repl.it/languages/python3). – Toni Sredanović May 24 '19 at 06:52
  • 1
    Sorry about that. I see now that it works on the online IDEs. I have no idea why it doesn't work on my system. – J...S May 24 '19 at 07:09
  • 1
    That's weird, I've tested it on my system too with both Python 3.6 and 2.7. Getting the correct output everywhere. If you do ever find out why you're getting `35:50.001` please let me know :D – Toni Sredanović May 24 '19 at 07:17
  • Sure thing. I too am wondering why it's so. And I've tried on a fresh python3.7 as well. – J...S May 24 '19 at 07:19