Skip to content

Commit

Permalink
Merge pull request #511 from MTrab:Fix-pytz-blocking-call
Browse files Browse the repository at this point in the history
Fix pytz blocking call warnings
  • Loading branch information
MTrab authored Jun 12, 2024
2 parents 79b4118 + f447177 commit 39e1192
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 23 deletions.
8 changes: 4 additions & 4 deletions config/configuration.yaml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
default_config:

logger:
default: warning
logs:
custom_components.energidataservice: debug
#logger:
# default: warning
# logs:
# custom_components.energidataservice: debug

# If you need to debug uncomment the line below (doc: https://www.home-assistant.io/integrations/debugpy/)
# debugpy:
7 changes: 4 additions & 3 deletions custom_components/energidataservice/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from importlib import import_module
from logging import getLogger

import homeassistant.util.dt as dt_util
import voluptuous as vol
from aiohttp import ClientConnectorError, ServerDisconnectedError
from homeassistant.config_entries import ConfigEntry
Expand Down Expand Up @@ -85,7 +86,8 @@ def __init__(
self._region = RegionHandler(
(entry.options.get(CONF_AREA) or entry.data.get(CONF_AREA)) or "FIXED"
)
self._tz = hass.config.time_zone
# self._tz = hass.config.time_zone
self._tz = dt_util.get_default_time_zone()
self._source = None
self.forecast = entry.options.get(CONF_ENABLE_FORECAST) or False
self.tariff = entry.options.get(CONF_ENABLE_TARIFFS) or False
Expand Down Expand Up @@ -202,8 +204,7 @@ async def update(self, dt=None) -> None: # type: ignore pylint: disable=unused-

midnight = datetime.strptime("23:59:59", "%H:%M:%S")
refresh = datetime.strptime(self.next_data_refresh, "%H:%M:%S")
datetime.utcnow()
now_local = datetime.now().astimezone(timezone(self._tz))
now_local = dt_util.now(self._tz)

_LOGGER.debug(
"Now: %s:%s:%s (local time)",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from datetime import datetime, timedelta
from logging import getLogger

import pytz
import homeassistant.util.dt as dt_util

from ...const import CO2INTERVAL, INTERVAL
from .regions import CO2REGIONS, REGIONS
Expand All @@ -24,15 +24,15 @@

def prepare_data(indata, date, tz) -> list: # pylint: disable=invalid-name
"""Get today prices."""
local_tz = pytz.timezone(tz)
local_tz = dt_util.get_default_time_zone()
reslist = []
for dataset in indata:
tmpdate = (
datetime.fromisoformat(dataset["HourUTC"])
.replace(tzinfo=pytz.utc)
.replace(tzinfo=dt_util.UTC)
.astimezone(local_tz)
)
tmp = INTERVAL(dataset["SpotPriceEUR"], local_tz.normalize(tmpdate))
tmp = INTERVAL(dataset["SpotPriceEUR"], tmpdate)
if date in tmp.hour.strftime("%Y-%m-%d"):
reslist.append(tmp)

Expand All @@ -41,15 +41,15 @@ def prepare_data(indata, date, tz) -> list: # pylint: disable=invalid-name

def prepare_co2_data(indata, date, tz) -> list: # pylint: disable=invalid-name
"""Prepare the CO2 data and return a list."""
local_tz = pytz.timezone(tz)
local_tz = dt_util.get_default_time_zone()
reslist = []
for dataset in indata:
tmpdate = (
datetime.fromisoformat(dataset["Minutes5UTC"])
.replace(tzinfo=pytz.utc)
.replace(tzinfo=dt_util.UTC)
.astimezone(local_tz)
)
tmp = CO2INTERVAL(dataset["CO2Emission"], local_tz.normalize(tmpdate))
tmp = CO2INTERVAL(dataset["CO2Emission"], tmpdate)
if date in tmp.hour.strftime("%Y-%m-%d"):
reslist.append(tmp)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import logging
from datetime import datetime, timedelta

import homeassistant.util.dt as dt_util
import pytz

from ...const import INTERVAL
Expand All @@ -22,16 +23,18 @@

DEFAULT_CURRENCY = "EUR"

TIMEZONE = pytz.timezone("Europe/Stockholm")

__all__ = ["REGIONS", "Connector", "DEFAULT_CURRENCY"]


def prepare_data(indata, date, tz) -> list: # pylint: disable=invalid-name
"""Get today prices."""
local_tz = pytz.timezone(tz)
local_tz = dt_util.get_default_time_zone()
reslist = []
for dataset in indata:
tmpdate = datetime.fromisoformat(dataset["HourUTC"]).astimezone(local_tz)
tmp = INTERVAL(dataset["SpotPriceEUR"], local_tz.normalize(tmpdate))
tmp = INTERVAL(dataset["SpotPriceEUR"], tmpdate)
if date in tmp.hour.strftime("%Y-%m-%d"):
reslist.append(tmp)

Expand Down Expand Up @@ -104,7 +107,6 @@ async def _fetch(self, enddate: datetime) -> str:
def _parse_json(self, data) -> list:
"""Parse json response."""
# Timezone for data from Nord Pool Group are "Europe/Stockholm"
timezone = pytz.timezone("Europe/Stockholm")

if "data" not in data:
return []
Expand All @@ -122,8 +124,8 @@ def _parse_json(self, data) -> list:
# Loop through response rows
for row in data["Rows"]:
start_hour = datetime.isoformat(
timezone.localize(datetime.fromisoformat(row["StartTime"])).astimezone(
pytz.utc
TIMEZONE.localize(datetime.fromisoformat(row["StartTime"])).astimezone(
dt_util.UTC
)
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from datetime import datetime
from logging import getLogger

import pytz
import homeassistant.util.dt as dt_util

from ...const import INTERVAL
from .regions import REGIONS
Expand All @@ -23,20 +23,20 @@

def prepare_data(indata, tz) -> list | None: # pylint: disable=invalid-name
"""Get today prices."""
local_tz = pytz.timezone(tz)
local_tz = dt_util.get_default_time_zone()
reslist = []
if not isinstance(indata, type(None)):
now = datetime.now()
for dataset in indata:
tmpdate = (
datetime.fromisoformat(dataset["utctime"])
.replace(tzinfo=pytz.utc)
.replace(tzinfo=dt_util.UTC)
.astimezone(local_tz)
)
if tmpdate.day != now.day:
if tmpdate.month == now.month and tmpdate.day < now.day:
continue
tmp = INTERVAL(dataset["prediction"], local_tz.normalize(tmpdate))
tmp = INTERVAL(dataset["prediction"], tmpdate)
reslist.append(tmp)
return reslist

Expand Down

0 comments on commit 39e1192

Please sign in to comment.