I have an application in which I need to parse timestamps of four different formats.
HH:MM:SS
HH:MM:SS.mm
MM:SS
MM:SS.mm
How can I write a function to parse any of these formats into a timedelta
object?
I have tried iterating through the characters one by one and break
ing when I see the :
, but my code is a mess, so I would rather not have it here as a baseline.
Here's a way to do it using
datetime.datetime.strptime()
:If you don't know ahead of time which format your input will be in, you can try all of them wrapped in a
try
/catch
block.strptime()
returns adatetime
object, so call the.time()
function to get only the time part. See this post for more details.Examples:
Output:
Or if you know the specific format, you can use
datetime.datetime.strptime(ts, f).time()
directly.Update 1
If you want to convert to
timedelta
s, you can do so using the output ofparse_timestamp()
and thetimedelta
constructor:Here is a related post that you may also find useful.