Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 6 commits into from Sep 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions homeassistant/components/bmw_connected_drive/__init__.py
@@ -1,5 +1,4 @@
"""Reads vehicle status from BMW connected drive portal."""
import datetime
import logging

import voluptuous as vol
Expand All @@ -8,6 +7,7 @@
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__)

Expand Down Expand Up @@ -100,7 +100,7 @@ def execute_service(call):

# 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,
Expand Down
13 changes: 8 additions & 5 deletions homeassistant/components/bom/sensor.py
Expand Up @@ -13,6 +13,7 @@
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,
Expand Down Expand Up @@ -240,7 +241,7 @@ def should_update(self):
# 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)
tsvi marked this conversation as resolved.
Show resolved Hide resolved
return now > update_due_at

Expand All @@ -251,8 +252,8 @@ def update(self):
_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
Expand All @@ -263,8 +264,10 @@ def update(self):

# 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

Expand Down
1 change: 0 additions & 1 deletion homeassistant/components/concord232/alarm_control_panel.py
Expand Up @@ -69,7 +69,6 @@ def __init__(self, url, name, code, mode):
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):
Expand Down
7 changes: 4 additions & 3 deletions homeassistant/components/concord232/binary_sensor.py
Expand Up @@ -12,6 +12,7 @@
)
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__)

Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -128,11 +129,11 @@ def is_on(self):

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"):
Expand Down
5 changes: 3 additions & 2 deletions homeassistant/components/demo/weather.py
@@ -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,
Expand All @@ -10,6 +10,7 @@
WeatherEntity,
)
from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT
import homeassistant.util.dt as dt_util

CONDITION_CLASSES = {
"cloudy": [],
Expand Down Expand Up @@ -147,7 +148,7 @@ def attribution(self):
@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:
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/dlna_dmr/media_player.py
@@ -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
Expand Down Expand Up @@ -43,6 +42,7 @@
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__)
Expand Down Expand Up @@ -241,14 +241,14 @@ async def async_update(self):
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")
Expand Down
3 changes: 2 additions & 1 deletion homeassistant/components/doorbird/camera.py
Expand Up @@ -8,6 +8,7 @@

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

Expand Down Expand Up @@ -77,7 +78,7 @@ def name(self):

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
Expand Down
5 changes: 3 additions & 2 deletions homeassistant/components/doorbird/switch.py
Expand Up @@ -3,6 +3,7 @@
import logging

from homeassistant.components.switch import SwitchDevice
import homeassistant.util.dt as dt_util

from . import DOMAIN as DOORBIRD_DOMAIN

Expand Down Expand Up @@ -66,7 +67,7 @@ def turn_on(self, **kwargs):
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):
Expand All @@ -75,6 +76,6 @@ def turn_off(self, **kwargs):

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
5 changes: 2 additions & 3 deletions homeassistant/components/ebusd/sensor.py
Expand Up @@ -3,6 +3,7 @@
import datetime

from homeassistant.helpers.entity import Entity
import homeassistant.util.dt as dt_util

from .const import DOMAIN

Expand Down Expand Up @@ -68,9 +69,7 @@ def device_state_attributes(self):
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
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/ios/notify.py
@@ -1,5 +1,4 @@
"""Support for iOS push notifications."""
from datetime import datetime, timezone
import logging

import requests
Expand All @@ -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, "
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/mobile_app/notify.py
@@ -1,6 +1,5 @@
"""Support for mobile_app push notifications."""
import asyncio
from datetime import datetime, timezone
import logging

import async_timeout
Expand Down Expand Up @@ -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, "
Expand Down
9 changes: 5 additions & 4 deletions homeassistant/components/ring/light.py
@@ -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

Expand Down Expand Up @@ -41,7 +42,7 @@ def __init__(self, device):
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."""
Expand Down Expand Up @@ -77,7 +78,7 @@ def _set_light(self, new_state):
"""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):
Expand All @@ -90,7 +91,7 @@ def turn_off(self, **kwargs):

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

Expand Down
9 changes: 5 additions & 4 deletions homeassistant/components/ring/switch.py
@@ -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

Expand Down Expand Up @@ -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
Expand All @@ -102,7 +103,7 @@ def icon(self):

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
5 changes: 3 additions & 2 deletions homeassistant/components/season/sensor.py
Expand Up @@ -8,6 +8,7 @@
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__)

Expand Down Expand Up @@ -104,7 +105,7 @@ def __init__(self, hass, hemisphere, season_tracking_type):
"""Initialize the season."""
self.hass = hass
self.hemisphere = hemisphere
self.datetime = datetime.now()
self.datetime = dt_util.utcnow().replace(tzinfo=None)
tsvi marked this conversation as resolved.
Show resolved Hide resolved
self.type = season_tracking_type
self.season = get_season(self.datetime, self.hemisphere, self.type)

Expand All @@ -125,5 +126,5 @@ def icon(self):

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)
3 changes: 1 addition & 2 deletions homeassistant/components/systemmonitor/sensor.py
@@ -1,5 +1,4 @@
"""Support for monitoring the local system."""
from datetime import datetime
import logging
import os
import socket
Expand Down Expand Up @@ -193,7 +192,7 @@ def update(self):
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)
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/upnp/sensor.py
@@ -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

Expand Down Expand Up @@ -199,10 +199,10 @@ async def async_update(self):

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:
Expand Down