Frage

from datetime import datetime, timedelta

frames_load = 0
times_start_dict = [{'timestamp': datetime(2013, 12, 21, 4, 36, 23)}, {'timestamp': datetime(2013, 12, 21, 4, 36, 23)}]
times_end_dict = [{'timestamp': datetime(2013, 12, 21, 4, 36, 53)}, {'timestamp': datetime(2013, 12, 21, 4, 36, 53)}]

for start in times_start_dict:
    for end in times_end_dict:         
        if check_startend(): #dummy function to check other value in dict to see if start/end times match; please comment this out and indent code block to reproduce error
            frames_load += end['timestamp'] - start['timestamp']
            print frames_load
            continue

Output:

Traceback (line 11): "frames_load += end['timestamp'] - start['timestamp']"

TypeError: unsupported operand type(s) for +=: 'int' and 'datetime.timedelta'

Some context:

I'm iterating over two lists consisting of dicts which contain datetime objects for start and end times, respectively. Once a start and end timedelta have been correctly matched (not shown), I find the time elapsed which becomes a timedelta object. I'm assigning it to frames_load so that in the next iteration, I can add the time elapsed (which should always be positive), figuring it's just like incrementing x += 1. However, I'm getting a TypeError which says to me that after the first iteration/calculation, frames_load is now an int and no longer a timedelta object.

How can I add timedeltas to frames_load so that it can display the aggregate/sum timedelta?

War es hilfreich?

Lösung

First, this code could not output 00:00:35, as frames_load=0 initially.

Second, error says it all, you can't add timedelta, i.e. end['timestamp'] - start['timestamp'], to integer, that is to 0.

If you want sum up cumulative timedelta, you should init frames_load=timedelta(). Or following code will do the trick:

times_start_dict = [{'timestamp': datetime(2013, 12, 21, 4, 36, 23)}, 
                    {'timestamp': datetime(2013, 12, 21, 4, 36, 23)}]
times_end_dict = [{'timestamp': datetime(2013, 12, 21, 4, 36, 25)}, 
                  {'timestamp': datetime(2013, 12, 21, 4, 36, 26)}]
print sum((end['timestamp'] - start['timestamp'] 
             for start, end in zip(times_start_dict, times_end_dict)),
          timedelta())

# 0:00:05
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top