Aritmética extraña con fechahoras y delta relativa
Frecuentes
Visto 1,324 equipos
1
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
>>> datetime.now() + relativedelta(days=2)
datetime.datetime(2014, 5, 30, 12, 24, 59, 173941)
>>> datetime.now() + relativedelta(days=1) * 2
# TypeError: integer argument expected, got float
Por otra parte:
>>> relativedelta(days=2) == relativedelta(days=1) * 2
True
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/relativedelta.py", line 261, in __radd__
day = min(calendar.monthrange(year, month)[1],
File "/usr/lib/python2.7/calendar.py", line 121, in monthrange
day1 = weekday(year, month, 1)
File "/usr/lib/python2.7/calendar.py", line 113, in weekday
return datetime.date(year, month, day).weekday()
TypeError: integer argument expected, got float
1 Respuestas
4
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 python datetime python-dateutil relativedelta or haz tu propia pregunta.
I don't get such a
TypeError
. yo obtengodatetime.datetime(2014, 5, 30, 12, 45, 2, 181770)
instead. What version ofpython-dateutil
have you got installed? I used Python 2.7 andpython-dateutil
2.2. - Martijn PietersEn 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. - Martijn PietersI 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@tobias_k: I still can't. Care to share an example session? The full traceback even would be of some use. - Martijn Pieters
@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 arelativedelta()
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. - Martijn Pieters