How to convert string of time to milliseconds?

Question:

I have a string which contains time (Hour-Minute-Second-Millisecond):

"00:00:12.750000"

I tried to convert it to milliseconds number without any success:

dt_obj = datetime.strptime(" 00:00:12.750000",'%H:%M:%S')
millisec = dt_obj.timestamp() * 1000

I’m getting error:

ValueError: time data ' 00:00:12.750000' does not match format '%H:%M:%S'

How can I convert it to milliseconds ? (it need to be 12*1000+750 = 12750)

Asked By: user3668129

||

Answers:

You can use python datetime.strptime() method to parse the time string into a datetime object.

So for that your code looks like:

from datetime import datetime

time_str = "00:00:12.750000"
time_obj = datetime.strptime(time_str, '%H:%M:%S.%f').time()

milliseconds = (time_obj.hour * 3600000) + (time_obj.minute * 60000) + (time_obj.second * 1000) + (time_obj.microsecond / 1000)

print(milliseconds)

Output:

12750.0
Answered By: NIKUNJ PATEL
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.