Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert string of time to milliseconds?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading