mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Fix carry when rounding time_since, time_until and timedelta_string (#185796)
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user