Change datetime.now() to dt_util.now() (#26582)

* Change datetime.now() to dt_util.now() in cases where the functionality should stay the same

These changes should not affect the functionality, rather cleanup our codebase.

In general we would like integrations to not to use datetime.now() unless there's a very good
reason for it, rather use our own dt_util.now() which makes the code aware of our current time
zone.

* Use datetime.utcnow() for season sensor to get offset-naive utc time

* Revert "Use datetime.utcnow() for season sensor to get offset-naive utc time"

This reverts commit 5f36463d9c7d52f8e11ffcec7e57dfbc7b21bdd1.

* BOM sensor last_updated should be UTC as well

* Run black

* Remove unused last_partition_update variable
pull/26714/head
Tsvi Mostovicz 2019-09-19 09:39:09 +03:00 committed by Martin Hjelmare
parent fccbaf3805
commit 80136f3591
16 changed files with 46 additions and 41 deletions

View File

@ -1,5 +1,4 @@
"""Reads vehicle status from BMW connected drive portal."""
import datetime
import logging
import voluptuous as vol
@ -8,6 +7,7 @@ from homeassistant.const import CONF_USERNAME, CONF_PASSWORD
from homeassistant.helpers import discovery
from homeassistant.helpers.event import track_utc_time_change
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__)
@ -100,7 +100,7 @@ def setup_account(account_config: dict, hass, name: str) -> "BMWConnectedDriveAc
# update every UPDATE_INTERVAL minutes, starting now
# this should even out the load on the servers
now = datetime.datetime.now()
now = dt_util.utcnow()
track_utc_time_change(
hass,
cd_account.update,

View File

@ -13,6 +13,7 @@ import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_MONITORED_CONDITIONS,
@ -240,7 +241,7 @@ class BOMCurrentData:
# Never updated before, therefore an update should occur.
return True
now = datetime.datetime.now()
now = dt_util.utcnow()
update_due_at = self.last_updated + datetime.timedelta(minutes=35)
return now > update_due_at
@ -251,8 +252,8 @@ class BOMCurrentData:
_LOGGER.debug(
"BOM was updated %s minutes ago, skipping update as"
" < 35 minutes, Now: %s, LastUpdate: %s",
(datetime.datetime.now() - self.last_updated),
datetime.datetime.now(),
(dt_util.utcnow() - self.last_updated),
dt_util.utcnow(),
self.last_updated,
)
return
@ -263,8 +264,10 @@ class BOMCurrentData:
# set lastupdate using self._data[0] as the first element in the
# array is the latest date in the json
self.last_updated = datetime.datetime.strptime(
str(self._data[0]["local_date_time_full"]), "%Y%m%d%H%M%S"
self.last_updated = dt_util.as_utc(
datetime.datetime.strptime(
str(self._data[0]["local_date_time_full"]), "%Y%m%d%H%M%S"
)
)
return

View File

@ -69,7 +69,6 @@ class Concord232Alarm(alarm.AlarmControlPanel):
self._url = url
self._alarm = concord232_client.Client(self._url)
self._alarm.partitions = self._alarm.list_partitions()
self._alarm.last_partition_update = datetime.datetime.now()
@property
def name(self):

View File

@ -12,6 +12,7 @@ from homeassistant.components.binary_sensor import (
)
from homeassistant.const import CONF_HOST, CONF_PORT
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__)
@ -53,7 +54,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
_LOGGER.debug("Initializing client")
client = concord232_client.Client(f"http://{host}:{port}")
client.zones = client.list_zones()
client.last_zone_update = datetime.datetime.now()
client.last_zone_update = dt_util.utcnow()
except requests.exceptions.ConnectionError as ex:
_LOGGER.error("Unable to connect to Concord232: %s", str(ex))
@ -128,11 +129,11 @@ class Concord232ZoneSensor(BinarySensorDevice):
def update(self):
"""Get updated stats from API."""
last_update = datetime.datetime.now() - self._client.last_zone_update
last_update = dt_util.utcnow() - self._client.last_zone_update
_LOGGER.debug("Zone: %s ", self._zone)
if last_update > datetime.timedelta(seconds=1):
self._client.zones = self._client.list_zones()
self._client.last_zone_update = datetime.datetime.now()
self._client.last_zone_update = dt_util.utcnow()
_LOGGER.debug("Updated from zone: %s", self._zone["name"])
if hasattr(self._client, "zones"):

View File

@ -1,5 +1,5 @@
"""Demo platform that offers fake meteorological data."""
from datetime import datetime, timedelta
from datetime import timedelta
from homeassistant.components.weather import (
ATTR_FORECAST_CONDITION,
@ -10,6 +10,7 @@ from homeassistant.components.weather import (
WeatherEntity,
)
from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT
import homeassistant.util.dt as dt_util
CONDITION_CLASSES = {
"cloudy": [],
@ -147,7 +148,7 @@ class DemoWeather(WeatherEntity):
@property
def forecast(self):
"""Return the forecast."""
reftime = datetime.now().replace(hour=16, minute=00)
reftime = dt_util.now().replace(hour=16, minute=00)
forecast_data = []
for entry in self._forecast:

View File

@ -1,6 +1,5 @@
"""Support for DLNA DMR (Device Media Renderer)."""
import asyncio
from datetime import datetime
from datetime import timedelta
import functools
import logging
@ -43,6 +42,7 @@ from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.typing import HomeAssistantType
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
from homeassistant.util import get_local_ip
_LOGGER = logging.getLogger(__name__)
@ -241,14 +241,14 @@ class DlnaDmrDevice(MediaPlayerDevice):
return
# do we need to (re-)subscribe?
now = datetime.now()
now = dt_util.utcnow()
should_renew = (
self._subscription_renew_time and now >= self._subscription_renew_time
)
if should_renew or not was_available and self._available:
try:
timeout = await self._device.async_subscribe_services()
self._subscription_renew_time = datetime.now() + timeout / 2
self._subscription_renew_time = dt_util.utcnow() + timeout / 2
except (asyncio.TimeoutError, aiohttp.ClientError):
self._available = False
_LOGGER.debug("Could not (re)subscribe")

View File

@ -8,6 +8,7 @@ import async_timeout
from homeassistant.components.camera import Camera, SUPPORT_STREAM
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.util.dt as dt_util
from . import DOMAIN as DOORBIRD_DOMAIN
@ -77,7 +78,7 @@ class DoorBirdCamera(Camera):
async def async_camera_image(self):
"""Pull a still image from the camera."""
now = datetime.datetime.now()
now = dt_util.utcnow()
if self._last_image and now - self._last_update < self._interval:
return self._last_image

View File

@ -3,6 +3,7 @@ import datetime
import logging
from homeassistant.components.switch import SwitchDevice
import homeassistant.util.dt as dt_util
from . import DOMAIN as DOORBIRD_DOMAIN
@ -66,7 +67,7 @@ class DoorBirdSwitch(SwitchDevice):
else:
self._state = self._doorstation.device.energize_relay(self._relay)
now = datetime.datetime.now()
now = dt_util.utcnow()
self._assume_off = now + self._time
def turn_off(self, **kwargs):
@ -75,6 +76,6 @@ class DoorBirdSwitch(SwitchDevice):
def update(self):
"""Wait for the correct amount of assumed time to pass."""
if self._state and self._assume_off <= datetime.datetime.now():
if self._state and self._assume_off <= dt_util.utcnow():
self._state = False
self._assume_off = datetime.datetime.min

View File

@ -3,6 +3,7 @@ import logging
import datetime
from homeassistant.helpers.entity import Entity
import homeassistant.util.dt as dt_util
from .const import DOMAIN
@ -68,9 +69,7 @@ class EbusdSensor(Entity):
if index < len(time_frame):
parsed = datetime.datetime.strptime(time_frame[index], "%H:%M")
parsed = parsed.replace(
datetime.datetime.now().year,
datetime.datetime.now().month,
datetime.datetime.now().day,
dt_util.now().year, dt_util.now().month, dt_util.now().day
)
schedule[item[0]] = parsed.isoformat()
return schedule

View File

@ -1,5 +1,4 @@
"""Support for iOS push notifications."""
from datetime import datetime, timezone
import logging
import requests
@ -25,7 +24,7 @@ def log_rate_limits(hass, target, resp, level=20):
"""Output rate limit log line at given level."""
rate_limits = resp["rateLimits"]
resetsAt = dt_util.parse_datetime(rate_limits["resetsAt"])
resetsAtTime = resetsAt - datetime.now(timezone.utc)
resetsAtTime = resetsAt - dt_util.utcnow()
rate_limit_msg = (
"iOS push notification rate limits for %s: "
"%d sent, %d allowed, %d errors, "

View File

@ -1,6 +1,5 @@
"""Support for mobile_app push notifications."""
import asyncio
from datetime import datetime, timezone
import logging
import async_timeout
@ -60,7 +59,7 @@ def log_rate_limits(hass, device_name, resp, level=logging.INFO):
rate_limits = resp[ATTR_PUSH_RATE_LIMITS]
resetsAt = rate_limits[ATTR_PUSH_RATE_LIMITS_RESETS_AT]
resetsAtTime = dt_util.parse_datetime(resetsAt) - datetime.now(timezone.utc)
resetsAtTime = dt_util.parse_datetime(resetsAt) - dt_util.utcnow()
rate_limit_msg = (
"mobile_app push notification rate limits for %s: "
"%d sent, %d allowed, %d errors, "

View File

@ -1,9 +1,10 @@
"""This component provides HA switch support for Ring Door Bell/Chimes."""
import logging
from datetime import datetime, timedelta
from datetime import timedelta
from homeassistant.components.light import Light
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.core import callback
import homeassistant.util.dt as dt_util
from . import DATA_RING_STICKUP_CAMS, SIGNAL_UPDATE_RING
@ -41,7 +42,7 @@ class RingLight(Light):
self._device = device
self._unique_id = self._device.id
self._light_on = False
self._no_updates_until = datetime.now()
self._no_updates_until = dt_util.utcnow()
async def async_added_to_hass(self):
"""Register callbacks."""
@ -77,7 +78,7 @@ class RingLight(Light):
"""Update light state, and causes HASS to correctly update."""
self._device.lights = new_state
self._light_on = new_state == ON_STATE
self._no_updates_until = datetime.now() + SKIP_UPDATES_DELAY
self._no_updates_until = dt_util.utcnow() + SKIP_UPDATES_DELAY
self.async_schedule_update_ha_state(True)
def turn_on(self, **kwargs):
@ -90,7 +91,7 @@ class RingLight(Light):
def update(self):
"""Update current state of the light."""
if self._no_updates_until > datetime.now():
if self._no_updates_until > dt_util.utcnow():
_LOGGER.debug("Skipping update...")
return

View File

@ -1,9 +1,10 @@
"""This component provides HA switch support for Ring Door Bell/Chimes."""
import logging
from datetime import datetime, timedelta
from datetime import timedelta
from homeassistant.components.switch import SwitchDevice
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.core import callback
import homeassistant.util.dt as dt_util
from . import DATA_RING_STICKUP_CAMS, SIGNAL_UPDATE_RING
@ -72,14 +73,14 @@ class SirenSwitch(BaseRingSwitch):
def __init__(self, device):
"""Initialize the switch for a device with a siren."""
super().__init__(device, "siren")
self._no_updates_until = datetime.now()
self._no_updates_until = dt_util.utcnow()
self._siren_on = False
def _set_switch(self, new_state):
"""Update switch state, and causes HASS to correctly update."""
self._device.siren = new_state
self._siren_on = new_state > 0
self._no_updates_until = datetime.now() + SKIP_UPDATES_DELAY
self._no_updates_until = dt_util.utcnow() + SKIP_UPDATES_DELAY
self.schedule_update_ha_state()
@property
@ -102,7 +103,7 @@ class SirenSwitch(BaseRingSwitch):
def update(self):
"""Update state of the siren."""
if self._no_updates_until > datetime.now():
if self._no_updates_until > dt_util.utcnow():
_LOGGER.debug("Skipping update...")
return
self._siren_on = self._device.siren > 0

View File

@ -8,6 +8,7 @@ from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_TYPE
from homeassistant.helpers.entity import Entity
from homeassistant import util
import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__)
@ -104,7 +105,7 @@ class Season(Entity):
"""Initialize the season."""
self.hass = hass
self.hemisphere = hemisphere
self.datetime = datetime.now()
self.datetime = dt_util.utcnow().replace(tzinfo=None)
self.type = season_tracking_type
self.season = get_season(self.datetime, self.hemisphere, self.type)
@ -125,5 +126,5 @@ class Season(Entity):
def update(self):
"""Update season."""
self.datetime = datetime.utcnow()
self.datetime = dt_util.utcnow().replace(tzinfo=None)
self.season = get_season(self.datetime, self.hemisphere, self.type)

View File

@ -1,5 +1,4 @@
"""Support for monitoring the local system."""
from datetime import datetime
import logging
import os
import socket
@ -193,7 +192,7 @@ class SystemMonitorSensor(Entity):
counters = psutil.net_io_counters(pernic=True)
if self.argument in counters:
counter = counters[self.argument][IO_COUNTER[self.type]]
now = datetime.now()
now = dt_util.utcnow()
if self._last_value and self._last_value < counter:
self._state = round(
(counter - self._last_value)

View File

@ -1,11 +1,11 @@
"""Support for UPnP/IGD Sensors."""
from datetime import datetime
import logging
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import HomeAssistantType
import homeassistant.util.dt as dt_util
from .const import DOMAIN as DOMAIN_UPNP, SIGNAL_REMOVE_SENSOR
@ -199,10 +199,10 @@ class PerSecondUPnPIGDSensor(UpnpSensor):
if self._last_value is None:
self._last_value = new_value
self._last_update_time = datetime.now()
self._last_update_time = dt_util.utcnow()
return
now = datetime.now()
now = dt_util.utcnow()
if self._is_overflowed(new_value):
self._state = None # temporarily report nothing
else: