From 17652e47608b8a3dd29c60856abfd079e4ea26a6 Mon Sep 17 00:00:00 2001 From: Raman Gupta <7243222+raman325@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:31:52 -0400 Subject: [PATCH] Fix timedelta_string showing 12 months instead of 1 year (#187648) Co-authored-by: Claude Opus 5.5 --- homeassistant/util/dt.py | 5 +++-- tests/util/test_dt.py | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/homeassistant/util/dt.py b/homeassistant/util/dt.py index bdfb265e7a74..6babfafb7fcd 100644 --- a/homeassistant/util/dt.py +++ b/homeassistant/util/dt.py @@ -337,8 +337,9 @@ def _get_timestring(timediff: float, precision: int = 1) -> str: 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]: + rounded_months = (timediff % factors[0]) // factors[1] + # 12 months are 5 days short of a year, so rounding to them ends the year + if rounded_months >= 12 and (months < 12 or current_factor == factors[1]): timediff += factors[0] - timediff % factors[0] break remainder %= current_factor diff --git a/tests/util/test_dt.py b/tests/util/test_dt.py index 8ebf056b239c..f0dcc77ab121 100644 --- a/tests/util/test_dt.py +++ b/tests/util/test_dt.py @@ -320,6 +320,10 @@ def test_time_remaining() -> None: (timedelta(days=29, hours=13), 1, "1 month"), (timedelta(days=364, hours=13), 2, "1 year"), (timedelta(days=350), 1, "1 year"), + (timedelta(days=360), 1, "1 year"), + (timedelta(days=364), 1, "1 year"), + (timedelta(days=365, hours=-1), 1, "1 year"), + (timedelta(days=729), 2, "2 years"), (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"),