Skip to content

Commit

Permalink
Use UTC datetimes internally (#73)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
pnbruckner authored Nov 20, 2024
1 parent 8ba9f76 commit 9a1be11
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions custom_components/illuminance/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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]
Expand Down

0 comments on commit 9a1be11

Please sign in to comment.