sdispater / pendulum

Python datetimes made easy
https://pendulum.eustace.io
MIT License
6.18k stars 381 forks source link

Error dividing Period by timedelta #382

Open emlyn opened 5 years ago

emlyn commented 5 years ago

The following snippet fails for me (using Python 3.7.3). It looks like pendulum is depending on a private method of timedelta (_to_microseconds), which does not exist in all versions:

> from datetime import timedelta
> from pendulum import datetime
> p = datetime(2019, 1, 1) - datetime(2019, 1, 1)
> d = timedelta(days=1)
> p/d
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-33-79e6ca0b60d8> in <module>
----> 1 p/d

~/.virtualenvs/test/lib/python3.7/site-packages/pendulum/period.py in __truediv__(self, other)
    325
    326     def __truediv__(self, other):
--> 327         return self.as_interval().__truediv__(other)
    328
    329     __div__ = __floordiv__

~/.virtualenvs/test/lib/python3.7/site-packages/pendulum/duration.py in __truediv__(self, other)
    357         usec = self._to_microseconds()
    358         if isinstance(other, timedelta):
--> 359             return usec / other._to_microseconds()
    360
    361         # Removing years/months approximation

AttributeError: 'datetime.timedelta' object has no attribute '_to_microseconds'
The-Fonz commented 3 years ago

I'm having this exact issue on Python 3.8.5 and Pendulum 2.1.2.

jacob-r-g commented 3 years ago

I am having this same issue

AlexisBRENON commented 2 months ago

Still facing this issue with Pendulum 3.0.0 and Python 3.11. My current workaround is to manually convert division terms to seconds (I don't mind the microsecond parts).

Python 3.11.9 (main, May  2 2024, 11:51:32) [GCC 13.2.1 20240417] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pendulum
>>> pendulum.__version__
'3.0.0'
>>> p = pendulum.Duration(hours=10)
>>> import datetime
>>> p2 = datetime.timedelta(hours=1)
>>> p / p2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/alexis/Public/GitHub/<redacted>/pendulum/duration.py", line 419, in __truediv__
    float, usec / other._to_microseconds()  # type: ignore[attr-defined]
                  ^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'datetime.timedelta' object has no attribute '_to_microseconds'. Did you mean: 'microseconds'?
>>> p.as_timedelta() / p2
10.0
>>> p.total_seconds() / p2.total_seconds()
10.0