Skip to content

Commit

Permalink
Merge pull request #210 from Snuffy2/Use-HASS-Time-Zone
Browse files Browse the repository at this point in the history
Use HASS Time Zone if defined
  • Loading branch information
Snuffy2 authored Sep 2, 2023
2 parents c5fc90a + 4ae970d commit 9734956
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions custom_components/places/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import os
import re
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

import homeassistant.helpers.entity_registry as er
import requests
Expand Down Expand Up @@ -177,10 +178,11 @@ def __init__(self, hass, config, config_entry, name, unique_id):
"""Initialize the sensor."""
self._attr_should_poll = True
_LOGGER.info(f"({name}) [Init] Places sensor: {name}")
_LOGGER.debug(f"({name}) [Init] Locale: {locale.getlocale()}")
_LOGGER.debug(f"({name}) [Init] System Locale: {locale.getlocale()}")
_LOGGER.debug(
f"({name}) [Init] Locale Date Format: {str(locale.nl_langinfo(locale.D_FMT))}"
f"({name}) [Init] System Locale Date Format: {str(locale.nl_langinfo(locale.D_FMT))}"
)
_LOGGER.debug(f"({name}) [Init] HASS TimeZone: {hass.config.time_zone}")

self._warn_if_device_tracker_prob = False
self._internal_attr = {}
Expand Down Expand Up @@ -2076,7 +2078,10 @@ def finalize_last_place_name(self, prev_last_place_name=None):
def do_update(self, reason):
"""Get the latest data and updates the states."""

now = datetime.now()
if self._hass.config.time_zone is not None:
now = datetime.now(tz=ZoneInfo(str(self._hass.config.time_zone)))
else:
now = datetime.now()
previous_attr = copy.deepcopy(self._internal_attr)

_LOGGER.info(f"({self.get_attr(CONF_NAME)}) Starting Update...")
Expand Down Expand Up @@ -2404,13 +2409,20 @@ def get_seconds_from_last_change(self, now):
else:
try:
changed_diff_sec = (now - last_changed).total_seconds()
except TypeError:
try:
changed_diff_sec = (datetime.now() - last_changed).total_seconds()
except (TypeError, OverflowError) as e:
_LOGGER.warning(
f"Error calculating the seconds between last change to now: {repr(e)}"
)
return 3600
except OverflowError as e:
_LOGGER.warning(
f"Error calculating the seconds between last change to now: {repr(e)}"
)
return 3600
else:
return changed_diff_sec
return changed_diff_sec

def _reset_attributes(self):
"""Resets attributes."""
Expand Down

0 comments on commit 9734956

Please sign in to comment.