Zaks
Zaks

Reputation: 700

unsupported operand type(s) for %: 'datetime.timedelta' and 'int'

My python code is as below:

if ( delta % 24 == 0):
    print "ONE DAY "

It gives error as TypeError: unsupported operand type(s) for %: 'datetime.timedelta' and 'int'

delta is of type datetime.timedelta

Please share your inputs to fix this error. Using pyton 2.7 due to project requirement

Upvotes: 0

Views: 7782

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

What about reading the doc for datetime.timedelta ? Or even just test it in your python shell :

>>> d = datetime.timedelta(hours=24)
>>> d
datetime.timedelta(1)
>>> dir(d)
['__abs__', '__add__', '__class__', '__delattr__', '__div__', '__doc__', '__eq__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__radd__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmul__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'days', 'max', 'microseconds', 'min', 'resolution', 'seconds', 'total_seconds']
>>> d.days
1
>>> d = datetime.timedelta(hours=8)
>>> d.days
0

As you can see, you already have the information at hand.

Note that if you need other computations based on hours (not days), you'll need to use delta.seconds / (60 * 60) - for some reasons I can't understand no one ever took care of adding an hours or minutes attributes to timedelta...

Upvotes: 0

gsamaras
gsamaras

Reputation: 73366

DateTime doesn't support modulo, thus the error you see.

This Python modulo support for datetime exists though.


Moreover, you could cast the second operand, so that the error goes away:

if ( ( d % timedelta(minutes = 24) ) == 0):
     print("ONE DAY")

which works in Python 3.6.1.

EDIT:

This won't work for Python 2.7.0, which was edited to OP's question. In that case, this may help: Manipulating DateTime and TimeDelta objects in python.

Upvotes: 5

Related Questions