python:添加timedeltas,int不支持的操作数类型

时间:2013-12-30 02:29:44

标签: python datetime timedelta

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

输出:

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

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

某些背景信息:

我正在迭代两个由dict组成的列表,这些列表分别包含开始和结束时间的datetime个对象。一旦开始和结束timedelta已正确匹配(未显示),我会找到成为timedelta对象的时间。我将它分配给frames_load,以便在下一次迭代中,我可以添加经过的时间(应该总是为正),这样就像递增x += 1一样。但是,我得到一个TypeError,它告诉我,在第一次迭代/计算之后,frames_load现在是int而不再是timedelta对象。

如何将timedelta添加到frames_load,以便它可以显示汇总/总和timedelta

1 个答案:

答案 0 :(得分:3)

首先,此代码最初无法00:00:35输出frames_load=0

其次,错误说明了一切,你不能将timedelta,即end['timestamp'] - start['timestamp']添加到整数,即0

如果你想总结累积时间,你应该初始化frames_load=timedelta()。或者以下代码可以解决问题:

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