How to construct a timedelta object from a simple string

priestc picture priestc · Jan 7, 2011 · Viewed 73.8k times · Source

I'm writing a function that needs a timedelta input to be passed in as a string. The user must enter something like "32m" or "2h32m", or even "4:13" or "5hr34m56s"... Is there a library or something that has this sort of thing already implemented?

Answer

metakermit picture metakermit · Sep 10, 2012

To me the most elegant solution, without having to resort to external libraries such as dateutil or manually parsing the input, is to use datetime's powerful strptime string parsing method.

from datetime import datetime, timedelta
# we specify the input and the format...
t = datetime.strptime("05:20:25","%H:%M:%S")
# ...and use datetime's hour, min and sec properties to build a timedelta
delta = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)

After this you can use your timedelta object as normally, convert it to seconds to make sure we did the correct thing etc.

print(delta)
assert(5*60*60+20*60+25 == delta.total_seconds())