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

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

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

If youre 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

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

from datetime import datetime

timezero = datetime.strptime(00:00:00.000, %H:%M:%S.%f)
(datetime.strptime(00:04:11.723, %H:%M:%S.%f) - timezero).total_seconds() * 1000

The basic idea is to use strptime() to parse your string to get a datetime object. Since datetime objects dont have a nice method for total seconds, but timedelta does, we subtract another datetime, which results in the timedelta were looking for. Now we can take total_seconds(). Multiply by 1000 and you have your answer (as a floating point number).

Leave a Reply

Your email address will not be published. Required fields are marked *