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)
>Solution :
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