pendulum icon indicating copy to clipboard operation
pendulum copied to clipboard

Duration division, multiplication and mod broken for month lengths.

Open gazpachoking opened this issue 1 year ago • 2 comments

  • [x] I am on the latest Pendulum version.
  • [x] I have searched the issues of this repo and believe that this is not a duplicate.
  • OS Version: Windows 11
  • Pendulum version: 3.0.0

Issue

When doing math on Duration objects, months are ignored. This is because it uses the _to_microseconds method which ignores the months attribute. https://github.com/sdispater/pendulum/blob/3e3fec6a5b66759078c5ae39c736ca95b78adbef/src/pendulum/duration.py#L356-L357 e.g. :

>>> pendulum.Duration(years=1)/pendulum.Duration(months=1)
Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2022.2.2\plugins\python\helpers\pydev\pydevconsole.py", line 364, in runcode
    coro = func()
  File "<input>", line 1, in <module>
  File "C:\Users\chase\PycharmProjects\Flexget\py310\lib\site-packages\pendulum\duration.py", line 419, in __truediv__
    float, usec / other._to_microseconds()  # type: ignore[attr-defined]
ZeroDivisionError: division by zero

>>> pendulum.Duration(months=1)*3.0
Duration()

gazpachoking avatar Jan 28 '24 01:01 gazpachoking

Duration only supports full months and years, hence floating-point multiplication is not supported.

@sdispater @Secrus I see two options here:

  • Raise an error when floating-point multiplication is applied on a Duration with years>0 and/or months>0.
  • Round up or down to the nearest integer as is done with __truediv__ https://github.com/sdispater/pendulum/blob/3e3fec6a5b66759078c5ae39c736ca95b78adbef/src/pendulum/duration.py#L431-L439

Benji19967 avatar Mar 08 '24 15:03 Benji19967