Aritmética extraña con fechahoras y delta relativa

Is it safe to multiply relativedelta objects? I'm seeing some weird and inconsistent behaviour, and can't find it documented what sorts of arithmetic are supported by this class (if any)

>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta
>>> + relativedelta(days=2)
datetime.datetime(2014, 5, 30, 12, 24, 59, 173941)
>>> + relativedelta(days=1) * 2
# TypeError: integer argument expected, got float

Por otra parte:

>>> relativedelta(days=2) == relativedelta(days=1) * 2

Full traceback (with python 2.7.5 y dateutil 1.5):

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/dateutil/", line 261, in __radd__
    day = min(calendar.monthrange(year, month)[1],
  File "/usr/lib/python2.7/", line 121, in monthrange
    day1 = weekday(year, month, 1)
  File "/usr/lib/python2.7/", line 113, in weekday
    return, month, day).weekday()
TypeError: integer argument expected, got float

preguntado el 28 de mayo de 14 a las 12:05

I don't get such a TypeError. yo obtengo datetime.datetime(2014, 5, 30, 12, 45, 2, 181770) instead. What version of python-dateutil have you got installed? I used Python 2.7 and python-dateutil 2.2. -

En cuanto a los is it safe to multiply: yes, the type specifically implements both __mul__ e __rmul__ methods for this use-case. But I cannot reproduce your problem at all. -

I can reproduce, using Python 2.7.5+. The exceptions seems to occur when you try to add a relativedelta that is the result of a multiplication, even when you do * 1 -

@tobias_k: I still can't. Care to share an example session? The full traceback even would be of some use. -

@tobias_k: the source code of __mul__ turns the other argument into a float, multiplies the relative components and turns the results back into integers. I don't see how that could lead to a relativedelta() instance that bombs out this way. A full traceback would at least help me trace back to a scenario where the error might occur, but that's sadly missing from this post. Hence my VtC as lacking info. -

1 Respuestas

Te has topado con un known bug in relativedelta's handling of multiplication, since fixed. It only affects Python 2.7 or newer (call signatures of certain functions were tightened).

Actualiza tu python-dateutils package to version 2.1 or newer.

Don't be put off by the 2.0-is-Python-3-only misinformation on the project documentation; 2.1 and 2.2 are Python 2 and 3 cross-compatible.

contestado el 28 de mayo de 14 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.