Search code examples
pythonpython-3.xpython-datetimepython-collections

Why does adding two Counters with timedelta values raise a TypeError?


I am trying to add two Counters, which contain timedeltas. Adding the Counters raises the following:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/collections/__init__.py", line 734, in __add__
    if newcount > 0:
TypeError: '>' not supported between instances of 'datetime.timedelta' and 'int'

This raises the exception:

from collections import Counter
from datetime import timedelta
a = Counter(time=timedelta(microseconds=167242))
a + a

However this does not:

b = timedelta(microseconds=167242)
b + b

Solution

  • A few things are getting in the way:

    1. Counter is designed to do discrete counting, that is, the values are integers.
    2. timedeltas don't define what it means to be compared to zero, though they could have.

    Looks like you will need to do your own Counter-like structure.