Bartłomiej Bartnicki Bartłomiej Bartnicki - 29 days ago 17
Python Question

Delta time string to datetime object

Given a string that looks like

"Hours:5 Minutes:34 Seconds:28"
or
"Minutes:34 Seconds:28"
, is there any pythonic way to convert it to a
datetime
object? I do not want to use a regex if there's an easier way.

Answer

Yes, there is. You can do it like this:

import time

datetime_string = "Hours:5 Minutes:34 Seconds:28"
if "Hours" in datetime_string:
    datetime_object = time.strptime(datetime_string, "Hours:%H Minutes:%M Seconds:%S")
elif "Minutes" in datetime_string:
    datetime_object = time.strptime(datetime_string, "Minutes:%M Seconds:%S")
else:
    datetime_object = time.strptime(datetime_string, "Seconds:%S")

Note: When You create datetime object, values that You do not provide will be filled with default values.So, in case datetime_string contains only seconds, hours and minutes will be set to 0.