Bartłomiej Bartnicki Bartłomiej Bartnicki - 1 year ago 209
Python Question

Delta time string to datetime object

Given a string that looks like

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

Answer Source

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")
    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download