Python parsing timeline

Possible duplicate:
How to build a timedelta object from a simple string

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

I am trying to find a time that is offset from the current time by the amount of time indicated on the line. I could use regular expressions to manually split 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 for this?

The formatting of the time.strptime() function seems to work during day / date strings, not arbitrary strings.

+4
source share
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) 
+6
source

re is not used, but sometimes it works more to understand regular expression than to write 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() takes the values โ€‹โ€‹of hours , minutes and seconds as arguments. Therefore, you can even do something stupid (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) 
+1
source

Source: https://habr.com/ru/post/1437309/


All Articles