Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse time string in python [duplicate]

Tags:

python

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.

like image 974
tpg2114 Avatar asked Oct 02 '12 01:10

tpg2114


2 Answers

import datetime
dur_str = "100:00:00"
h, m, s = map(int, dur_str.split(':'))
dur = datetime.timedelta(hours=h, minutes=m, seconds=s)
like image 142
nneonneo Avatar answered Oct 13 '22 17:10

nneonneo


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)
like image 34
monkut Avatar answered Oct 13 '22 16:10

monkut