Home > Software engineering >  Best way to convert a string to milliseconds in Python
Best way to convert a string to milliseconds in Python

Time:08-11

To convert the amount of milliseconds represented by a string I created the following function:

time_str = '1:16.435'

def milli(time_str):
  m, s = time_str.split(':')
  return int(int(m) * 60000   float(s) * 1000)

milli(time_str)

But I'm wondering if there is a native Python function to do this directly.

CodePudding user response:

You can easily make it longer and more complicated with datetime:

import datetime
dateobj=datetime.datetime.strptime("1:16.435","%M:%S.%f")
timeobj=dateobj.time()
print(timeobj.minute*60000 timeobj.second*1000 timeobj.microsecond/1000)
76435.0

Now you have 2 additions, 2 multiplications, and even a division. And the bonus points for loading a package, of course. I like your original code more.

CodePudding user response:

Since you're looking for functions to do this for you, you can take advantage of TimeDelta object which has .total_seconds(). This way you don't have to do that calculation. Just create your datetime objects then subtract them:

from datetime import datetime

datetime_obj = datetime.strptime("1:16.435", "%M:%S.%f")
start_time = datetime(1900, 1, 1)
print((datetime_obj - start_time).total_seconds() * 1000)

output:

76435.0

The reason for choosing datetime(1900, 1, 1) is that when you use strptime with that format it fills the rest to make this form: 1900-01-01 00:01:16.435000.


If your string changes to have Hour for example, you just need to change your format and it works as expected. No need to change your formula and add another calculation:

datetime.strptime("1:1:16.435", "%H:%M:%S.%f")
start_time = datetime(1900, 1, 1)
print((datetime_obj - start_time).total_seconds() * 1000)
  • Related