2

I have a list of times that are in following format:

Hour:Minue:Second.Microseconds

File looks like this:

0:06:50.137529
0:08:55.439963
0:06:19.179093
0:07:16.680906
0:31:55.778010
0:16:56.940836

Is there a Python function or set of commands that will let me add all of these values together?

I initially "build" these values with the following code:

optimize_times = []
starting_time=(datetime.now())
ending_time=(datetime.now())
optimize_times.append(str(ending_time-starting_time))
2
  • Yes, timedelta, but it's not clear to me why you call str() on your results. Commented Nov 20, 2018 at 21:24
  • Without using the str function the value resulted in a timedelta function being output Commented Nov 20, 2018 at 21:37

1 Answer 1

1

You can use datetime.timedelta from the standard library:

from datetime import timedelta

L = ['0:06:50.137529', '0:08:55.439963', '0:06:19.179093',
     '0:07:16.680906', '0:31:55.778010', '0:16:56.940836']

def str_to_td(x):
    hrs, mins, sec_micro = x.split(':')
    secs, msecs = map(int, sec_micro.split('.'))
    return timedelta(hours=int(hrs), minutes=int(mins), seconds=secs, microseconds=msecs)

res = sum(map(str_to_td, L), timedelta())

# datetime.timedelta(0, 4694, 156337)

Note the output of this is a timedelta object. If this isn't the format your desire, you'll need to convert back to a string with additional logic.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that's exactly what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.