Fix carry when rounding time_since, time_until and timedelta_string (#185796)

This commit is contained in:
Jay Hemnani
2026-10-20 15:24:22 +00:00
committed by GitHub
parent 208b518080
commit aa9365d304
2 changed files with 26 additions and 0 deletions
+16
View File
@@ -327,6 +327,22 @@ def _get_timestring(timediff: float, precision: int = 1) -> str:
factors = (365 * 24 * 60 * 60, 30 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60, 1)
# Round at the last shown unit up front, so it carries into the larger units
remainder = timediff
current_precision = 0
for current_factor in factors:
if remainder < current_factor:
continue
current_precision += 1
if current_precision == precision:
months = (timediff % factors[0]) // factors[1]
timediff += round(remainder / current_factor) * current_factor - remainder
# 12 months are 5 days short of a year, so rounding up to them ends the year
if months < 12 <= (timediff % factors[0]) // factors[1]:
timediff += factors[0] - timediff % factors[0]
break
remainder %= current_factor
result_string: str = ""
current_precision = 0
+10
View File
@@ -313,6 +313,16 @@ def test_time_remaining() -> None:
(timedelta(hours=1, minutes=54, seconds=33), 0, "1 hour 54 minutes 33 seconds"),
(timedelta(hours=-1), 1, "1 hour"),
(timedelta(hours=-1, minutes=-30), 2, "1 hour 30 minutes"),
(timedelta(minutes=59, seconds=45), 1, "1 hour"),
(timedelta(hours=1, minutes=59, seconds=45), 2, "2 hours"),
(timedelta(hours=23, minutes=59, seconds=45), 2, "1 day"),
(timedelta(days=1, minutes=59, seconds=45), 2, "1 day 1 hour"),
(timedelta(days=29, hours=13), 1, "1 month"),
(timedelta(days=364, hours=13), 2, "1 year"),
(timedelta(days=350), 1, "1 year"),
(timedelta(days=724, hours=23, minutes=59, seconds=50), 2, "2 years"),
(timedelta(days=724, hours=13), 3, "2 years"),
(timedelta(days=380, hours=23, minutes=59, seconds=50), 2, "1 year 16 days"),
],
)
def test_timedelta_string(delta: timedelta, precision: int, expected: str) -> None: