user11528241
user11528241

Reputation:

Is there a more efficient way to convert milliseconds to this format "{minutes}:{seconds}"?

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?

Upvotes: 0

Views: 2450

Answers (2)

Toni Sredanović
Toni Sredanović

Reputation: 2412

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

Upvotes: 1

gmds
gmds

Reputation: 19895

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'

Upvotes: 5

Related Questions