Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/pendulum/duration.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,13 @@ def __mul__(self, other: int | float) -> Self:
usec = self._to_microseconds()
a, b = other.as_integer_ratio()

return self.__class__(0, 0, _divide_and_round(usec * a, b))
return self.__class__(
0,
0,
_divide_and_round(usec * a, b),
years=_divide_and_round(self._years * a, b),
months=_divide_and_round(self._months * a, b),
)

return NotImplemented

Expand Down
34 changes: 34 additions & 0 deletions tests/duration/test_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,40 @@ def test_multiply():
assert_duration(mul, 4, 6, 9, 5, 0, 1, 9, 44444)


def test_multiply_float():
# A float factor must scale years and months just like an int factor (and
# like float division already does). Regression: Duration.__mul__ with a
# float dropped the years/months components entirely.
it = pendulum.duration(
years=2, months=3, weeks=4, days=6, seconds=34, microseconds=522222
)
mul = it * 2.0

assert isinstance(mul, pendulum.Duration)
assert_duration(mul, 4, 6, 9, 5, 0, 1, 9, 44444)

mul = 2.0 * it

assert isinstance(mul, pendulum.Duration)
assert_duration(mul, 4, 6, 9, 5, 0, 1, 9, 44444)

# A whole-valued float must match the integer result exactly.
it = pendulum.duration(years=1, months=6, days=2, seconds=35, microseconds=522222)
by_int = it * 3
by_float = it * 3.0

assert (by_float.years, by_float.months) == (by_int.years, by_int.months)
assert by_float.total_seconds() == by_int.total_seconds()

# A non-integer factor rounds years/months, mirroring float division.
it = pendulum.duration(years=2, months=4, days=2, seconds=35, microseconds=522222)
mul = it * 1.5

assert isinstance(mul, pendulum.Duration)
assert mul.years == 3
assert mul.months == 6


def test_divide():
it = pendulum.duration(days=2, seconds=34, microseconds=522222)
mul = it / 2
Expand Down