5

Possible Duplicate:
How to construct a timedelta object from a simple string

I have a string that is in the format hours:minutes:seconds but it is not a time of day but a duration. For example, 100:00:00 means 100 hours.

I am trying to find the time that is offset from the current time by the amount of time specified in the string. I could use regular expressions to manually pull apart the time string and convert it to seconds and add it to the floating point returned by time.time(), but is there a time function to do this?

The time.strptime() function formatting seems to work on time of day/date strings and not arbitrary strings.

Community
  • 1
  • 1
tpg2114
  • 14,112
  • 6
  • 42
  • 57

2 Answers2

7
import datetime
dur_str = "100:00:00"
h, m, s = map(int, dur_str.split(':'))
dur = datetime.timedelta(hours=h, minutes=m, seconds=s)
Community
  • 1
  • 1
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • nice! forgot you can pass the hours, minutes, seconds values directly. – monkut Oct 02 '12 at 01:41
  • This won't work for shorter formats like 'mm:ss', though.. – Nickolay Jan 12 '14 at 13:43
  • To quote the asker, "I have a string that is in the format `hours:minutes:seconds`..." It's actually really easy to make this handle short formats; just condition on the number of elements from the `.split(':')`. – nneonneo Feb 26 '14 at 01:35
1

not using re but sometimes it's more work to understand the regex than write the python.

>>> import datetime
>>> time_str = "100:00:00"
>>> hours, minutes, seconds = [int(i) for i in time_str.split(":")]
>>> time_in_seconds = hours * 60 * 60 + minutes * 60 + seconds
>>> time_in_seconds
360000
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2012, 10, 2, 10, 24, 6, 639000)
>>> new_time = now + datetime.timedelta(seconds=time_in_seconds)
>>> new_time
datetime.datetime(2012, 10, 6, 14, 24, 6, 639000)

As nneonneo pointed out datetime.timedelta() accepts the hours, minutes, and seconds as arguments. So you can even do something silly like this (not recommended):

>>> datetime.timedelta(**{k:v for k,v in zip(["hours", "minutes", "seconds"], [int(i) for i in "100:00:00".split(":")])})
datetime.timedelta(4, 14400)
monkut
  • 42,176
  • 24
  • 124
  • 155