Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HH:MM:SS.micro string to microseconds?

I'm sure there must be a better way to convert a string like 00:04:11.723 to microseconds like this:

ms = timestring.split('.')
pt = ms[0].split(':')
sec = int(pt[0]) * 3600 + int(pt[1]) * 60 + int(pt[2])
st = sec * 1000 + int(ms[1])

but yet I didn't find it.

like image 523
Helmi Avatar asked Apr 27 '18 19:04

Helmi


2 Answers

This is one way using only datetime.timedelta:

from datetime import timedelta

x = '00:04:11.723'

h, m, s = map(float, x.split(':'))
res = timedelta(hours=h, minutes=m, seconds=s).total_seconds() * 1000

# 251723.0
like image 68
jpp Avatar answered Sep 28 '22 16:09

jpp


If you're not opposed to third party libraries, pandas.Timedelta might be useful for you:

import pandas as pd
pd.Timedelta(timestring).total_seconds()*1000

This returns: 251723.0

like image 20
sacuL Avatar answered Sep 28 '22 16:09

sacuL