From e0d39a41d54a4e7beec9cca11ffccc5f1f8afb4c Mon Sep 17 00:00:00 2001 From: Harri Kapanen Date: Sun, 5 Jan 2025 14:14:03 +0200 Subject: [PATCH] Make attributes' departure time timezone-aware (#102) --- custom_components/digitransit/sensor.py | 5 +++-- custom_components/digitransit/utils.py | 8 ++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/custom_components/digitransit/sensor.py b/custom_components/digitransit/sensor.py index ed0f4fc..85c0f4a 100644 --- a/custom_components/digitransit/sensor.py +++ b/custom_components/digitransit/sensor.py @@ -4,7 +4,7 @@ from homeassistant.components.sensor import SensorEntity, SensorEntityDescription from homeassistant.const import UnitOfTime - +from zoneinfo import ZoneInfo from .const import DOMAIN from .coordinator import DigitransitDataUpdateCoordinator from .entity import DigitransitEntity @@ -64,12 +64,13 @@ def native_unit_of_measurement(self): @property def extra_state_attributes(self): """Attributes contain a list of the next few departures.""" + timezone = ZoneInfo(self.hass.config.time_zone) departure_list = ( self.coordinator.data.get("data") .get("stop") .get("stoptimesWithoutPatterns") ) - departure_list = list(map(formatDepartureRow, departure_list)) + departure_list = [formatDepartureRow(row, timezone) for row in departure_list] return {"departures": departure_list} @property diff --git a/custom_components/digitransit/utils.py b/custom_components/digitransit/utils.py index c927575..14c2580 100644 --- a/custom_components/digitransit/utils.py +++ b/custom_components/digitransit/utils.py @@ -1,11 +1,11 @@ """Transform data for display.""" -from datetime import datetime +from datetime import datetime, timedelta import math -def formatDepartureRow(row): +def formatDepartureRow(row, timezone): """Simplify the departure information for use in the attribute.""" - row['scheduledDeparture'] = datetime.fromtimestamp(row['serviceDay'] + row['scheduledDeparture']) - row['realtimeDeparture'] = datetime.fromtimestamp(row['serviceDay'] + row['realtimeDeparture']) + row['scheduledDeparture'] = datetime.fromtimestamp(row['serviceDay'], timezone) + timedelta(seconds=row['scheduledDeparture']) + row['realtimeDeparture'] = datetime.fromtimestamp(row['serviceDay'], timezone) + timedelta(seconds=row['realtimeDeparture']) row['route'] = row.pop('trip')['routeShortName'] row.pop('serviceDay') return row