From c0bb48b53f54002b3813d05a283456dd6e27a001 Mon Sep 17 00:00:00 2001 From: Phil Bruckner Date: Thu, 14 Nov 2024 09:02:19 -0600 Subject: [PATCH] Use UTC datetimes internally Python datetime object comparisons and math don't work as expected when the objects are aware and have the same tzinfo attribute. Basically, the fold attribute is ignored in this case, which can lead to wrong results. Avoid this problem by using aware times in UTC internally. Only use local time zone for user visible attributes. --- custom_components/illuminance/sensor.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/custom_components/illuminance/sensor.py b/custom_components/illuminance/sensor.py index fc5b449..3db9814 100644 --- a/custom_components/illuminance/sensor.py +++ b/custom_components/illuminance/sensor.py @@ -351,7 +351,7 @@ async def async_update(self) -> None: return try: - value = self._calculate_illuminance(dt_util.now().replace(microsecond=0)) + value = self._calculate_illuminance(dt_util.utcnow().replace(microsecond=0)) except AbortUpdate: return @@ -492,11 +492,13 @@ def _calculate_illuminance(self, now: datetime) -> Num: def _astral_event(self, event: str, date_or_dt: date | datetime) -> Any: """Get astral event.""" loc, elev = cast(tuple[Location, Elevation], self.hass.data[DOMAIN]) - return getattr(loc, event)(date_or_dt, observer_elevation=elev) + if event == "solar_elevation": + return getattr(loc, event)(date_or_dt, observer_elevation=elev) + return getattr(loc, event)(date_or_dt, local=False, observer_elevation=elev) def _sun_factor(self, now: datetime) -> Num: """Calculate sun factor.""" - now_date = now.date() + now_date = dt_util.as_local(now).date() if self._sun_data and self._sun_data[0] == now_date: (sunrise_begin, sunrise_end, sunset_begin, sunset_end) = self._sun_data[1]