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

Import util.dt as dt_util in components/[g-i]* #93759

Merged
merged 1 commit into from
May 29, 2023
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
8 changes: 5 additions & 3 deletions homeassistant/components/gdacs/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .const import DEFAULT_ICON, DOMAIN, FEED

Expand Down Expand Up @@ -93,10 +93,12 @@ def _update_from_status_info(self, status_info):
"""Update the internal state from the provided information."""
self._status = status_info.status
self._last_update = (
dt.as_utc(status_info.last_update) if status_info.last_update else None
dt_util.as_utc(status_info.last_update) if status_info.last_update else None
)
if status_info.last_update_successful:
self._last_update_successful = dt.as_utc(status_info.last_update_successful)
self._last_update_successful = dt_util.as_utc(
status_info.last_update_successful
)
else:
self._last_update_successful = None
self._last_timestamp = status_info.last_timestamp
Expand Down
8 changes: 5 additions & 3 deletions homeassistant/components/geonetnz_quakes/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .const import DOMAIN, FEED

Expand Down Expand Up @@ -94,10 +94,12 @@ def _update_from_status_info(self, status_info):
"""Update the internal state from the provided information."""
self._status = status_info.status
self._last_update = (
dt.as_utc(status_info.last_update) if status_info.last_update else None
dt_util.as_utc(status_info.last_update) if status_info.last_update else None
)
if status_info.last_update_successful:
self._last_update_successful = dt.as_utc(status_info.last_update_successful)
self._last_update_successful = dt_util.as_utc(
status_info.last_update_successful
)
else:
self._last_update_successful = None
self._last_timestamp = status_info.last_timestamp
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/geonetnz_volcano/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import dt
from homeassistant.util import dt as dt_util
from homeassistant.util.unit_conversion import DistanceConverter

from .const import (
Expand Down Expand Up @@ -124,9 +124,9 @@ def _update_from_feed(self, feed_entry, last_update, last_update_successful):
self._alert_level = feed_entry.alert_level
self._activity = feed_entry.activity
self._hazards = feed_entry.hazards
self._feed_last_update = dt.as_utc(last_update) if last_update else None
self._feed_last_update = dt_util.as_utc(last_update) if last_update else None
self._feed_last_update_successful = (
dt.as_utc(last_update_successful) if last_update_successful else None
dt_util.as_utc(last_update_successful) if last_update_successful else None
)

@property
Expand Down
10 changes: 7 additions & 3 deletions homeassistant/components/google/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
async_track_point_in_utc_time,
async_track_time_interval,
)
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .const import (
CONF_CALENDAR_ACCESS,
Expand All @@ -51,7 +51,9 @@ class DeviceAuth(AuthImplementation):
async def async_resolve_external_data(self, external_data: Any) -> dict:
"""Resolve a Google API Credentials object to Home Assistant token."""
creds: Credentials = external_data[DEVICE_AUTH_CREDS]
delta = creds.token_expiry.replace(tzinfo=datetime.timezone.utc) - dt.utcnow()
delta = (
creds.token_expiry.replace(tzinfo=datetime.timezone.utc) - dt_util.utcnow()
)
_LOGGER.debug(
"Token expires at %s (in %s)", creds.token_expiry, delta.total_seconds()
)
Expand Down Expand Up @@ -108,7 +110,9 @@ def creds(self) -> Credentials | None:
def async_start_exchange(self) -> None:
"""Start the device auth exchange flow polling."""
_LOGGER.debug("Starting exchange flow")
max_timeout = dt.utcnow() + datetime.timedelta(seconds=EXCHANGE_TIMEOUT_SECONDS)
max_timeout = dt_util.utcnow() + datetime.timedelta(
seconds=EXCHANGE_TIMEOUT_SECONDS
)
# For some reason, oauth.step1_get_device_and_user_codes() returns a datetime
# object without tzinfo. For the comparison below to work, it needs one.
user_code_expiry = self._device_flow_info.user_code_expiry.replace(
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/google_assistant/trait.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
)
from homeassistant.core import DOMAIN as HA_DOMAIN
from homeassistant.helpers.network import get_url
from homeassistant.util import color as color_util, dt
from homeassistant.util import color as color_util, dt as dt_util
from homeassistant.util.percentage import (
ordered_list_item_to_percentage,
percentage_to_ordered_list_item,
Expand Down Expand Up @@ -2218,7 +2218,7 @@ async def execute(self, command, data, params, challenge):
rel_position = params["relativePositionMs"] / 1000
seconds_since = 0 # Default to 0 seconds
if self.state.state == STATE_PLAYING:
now = dt.utcnow()
now = dt_util.utcnow()
upd_at = self.state.attributes.get(
media_player.ATTR_MEDIA_POSITION_UPDATED_AT, now
)
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/google_wifi/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import Throttle, dt
from homeassistant.util import Throttle, dt as dt_util

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -212,7 +212,7 @@ def data_format(self):
elif attr_key == ATTR_UPTIME:
sensor_value = round(sensor_value / (3600 * 24), 2)
elif attr_key == ATTR_LAST_RESTART:
last_restart = dt.now() - timedelta(seconds=sensor_value)
last_restart = dt_util.now() - timedelta(seconds=sensor_value)
sensor_value = last_restart.strftime("%Y-%m-%d %H:%M:%S")
elif attr_key == ATTR_STATUS:
if sensor_value:
Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/growatt_server/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import Throttle, dt
from homeassistant.util import Throttle, dt as dt_util

from .const import (
CONF_PLANT_ID,
Expand Down Expand Up @@ -234,10 +234,10 @@ def update(self):
sorted_keys = sorted(mix_chart_entries)

# Create datetime from the latest entry
date_now = dt.now().date()
last_updated_time = dt.parse_time(str(sorted_keys[-1]))
date_now = dt_util.now().date()
last_updated_time = dt_util.parse_time(str(sorted_keys[-1]))
mix_detail["lastdataupdate"] = datetime.datetime.combine(
date_now, last_updated_time, dt.DEFAULT_TIME_ZONE
date_now, last_updated_time, dt_util.DEFAULT_TIME_ZONE
)

# Dashboard data is largely inaccurate for mix system but it is the only
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/here_travel_time/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, CONF_MODE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .const import (
CONF_ARRIVAL_TIME,
Expand Down Expand Up @@ -32,8 +32,8 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
"""Set up HERE Travel Time from a config entry."""
api_key = config_entry.data[CONF_API_KEY]

arrival = dt.parse_time(config_entry.options.get(CONF_ARRIVAL_TIME, ""))
departure = dt.parse_time(config_entry.options.get(CONF_DEPARTURE_TIME, ""))
arrival = dt_util.parse_time(config_entry.options.get(CONF_ARRIVAL_TIME, ""))
departure = dt_util.parse_time(config_entry.options.get(CONF_DEPARTURE_TIME, ""))

here_travel_time_config = HERETravelTimeConfig(
destination_latitude=config_entry.data.get(CONF_DESTINATION_LATITUDE),
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/here_travel_time/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.location import find_coordinates
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util import dt
from homeassistant.util import dt as dt_util
from homeassistant.util.unit_conversion import DistanceConverter

from .const import DEFAULT_SCAN_INTERVAL, DOMAIN, ROUTE_MODE_FASTEST
Expand Down Expand Up @@ -336,7 +336,7 @@ def build_hass_attribution(sections: list[dict[str, Any]]) -> str | None:

def next_datetime(simple_time: time) -> datetime:
"""Take a time like 08:00:00 and combine it with the current date."""
combined = datetime.combine(dt.start_of_local_day(), simple_time)
combined = datetime.combine(dt_util.start_of_local_day(), simple_time)
if combined < datetime.now():
combined = combined + timedelta(days=1)
return combined
6 changes: 3 additions & 3 deletions homeassistant/components/hydrawise/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .const import DOMAIN, LOGGER
from .coordinator import HydrawiseDataUpdateCoordinator
Expand Down Expand Up @@ -86,7 +86,7 @@ def _handle_coordinator_update(self) -> None:
else: # _sensor_type == 'next_cycle'
next_cycle = min(relay_data["time"], TWO_YEAR_SECONDS)
LOGGER.debug("New cycle time: %s", next_cycle)
self._attr_native_value = dt.utc_from_timestamp(
dt.as_timestamp(dt.now()) + next_cycle
self._attr_native_value = dt_util.utc_from_timestamp(
dt_util.as_timestamp(dt_util.now()) + next_cycle
)
super()._handle_coordinator_update()
4 changes: 2 additions & 2 deletions homeassistant/components/iotawatt/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .const import DOMAIN, VOLT_AMPERE_REACTIVE, VOLT_AMPERE_REACTIVE_HOURS
from .coordinator import IotawattUpdater
Expand Down Expand Up @@ -203,7 +203,7 @@ def _handle_coordinator_update(self) -> None:
return

if (begin := self._sensor_data.getBegin()) and (
last_reset := dt.parse_datetime(begin)
last_reset := dt_util.parse_datetime(begin)
):
self._attr_last_reset = last_reset

Expand Down
4 changes: 2 additions & 2 deletions tests/components/github/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from homeassistant.components.github.const import DOMAIN, FALLBACK_UPDATE_INTERVAL
from homeassistant.core import HomeAssistant
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .common import TEST_REPOSITORY

Expand Down Expand Up @@ -42,7 +42,7 @@ async def test_sensor_updates_with_empty_release_array(
headers=headers,
)

async_fire_time_changed(hass, dt.utcnow() + FALLBACK_UPDATE_INTERVAL)
async_fire_time_changed(hass, dt_util.utcnow() + FALLBACK_UPDATE_INTERVAL)
await hass.async_block_till_done()

new_state = hass.states.get(TEST_SENSOR_ENTITY)
Expand Down
6 changes: 3 additions & 3 deletions tests/components/google_assistant/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from homeassistant.config import async_process_ha_core_config
from homeassistant.core import HomeAssistant, State
from homeassistant.setup import async_setup_component
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from . import MockConfig

Expand Down Expand Up @@ -128,7 +128,7 @@ async def test_config_local_sdk(
assert config.is_local_connected is True
with patch(
"homeassistant.components.google_assistant.helpers.utcnow",
return_value=dt.utcnow() + timedelta(seconds=90),
return_value=dt_util.utcnow() + timedelta(seconds=90),
):
assert config.is_local_connected is False

Expand Down Expand Up @@ -255,7 +255,7 @@ async def test_agent_user_id_storage(
}

async def _check_after_delay(data):
async_fire_time_changed(hass, dt.utcnow() + timedelta(seconds=2))
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=2))
await hass.async_block_till_done()

assert (
Expand Down
4 changes: 2 additions & 2 deletions tests/components/hyperion/test_light.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.util import dt
from homeassistant.util import dt as dt_util
import homeassistant.util.color as color_util

from . import (
Expand Down Expand Up @@ -1370,7 +1370,7 @@ async def test_lights_can_be_enabled(hass: HomeAssistant) -> None:

async_fire_time_changed(
hass,
dt.utcnow() + timedelta(seconds=RELOAD_AFTER_UPDATE_DELAY + 1),
dt_util.utcnow() + timedelta(seconds=RELOAD_AFTER_UPDATE_DELAY + 1),
)
await hass.async_block_till_done()

Expand Down
4 changes: 2 additions & 2 deletions tests/components/hyperion/test_switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.util import dt, slugify
from homeassistant.util import dt as dt_util, slugify

from . import (
TEST_CONFIG_ENTRY_ID,
Expand Down Expand Up @@ -215,7 +215,7 @@ async def test_switches_can_be_enabled(hass: HomeAssistant) -> None:

async_fire_time_changed(
hass,
dt.utcnow() + timedelta(seconds=RELOAD_AFTER_UPDATE_DELAY + 1),
dt_util.utcnow() + timedelta(seconds=RELOAD_AFTER_UPDATE_DELAY + 1),
)
await hass.async_block_till_done()

Expand Down
4 changes: 2 additions & 2 deletions tests/components/image_upload/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from homeassistant.components.websocket_api import const as ws_const
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as util_dt
from homeassistant.util import dt as dt_util

from . import TEST_IMAGE

Expand All @@ -21,7 +21,7 @@ async def test_upload_image(
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test we can upload an image."""
now = util_dt.utcnow()
now = dt_util.utcnow()

with tempfile.TemporaryDirectory() as tempdir, patch.object(
hass.config, "path", return_value=tempdir
Expand Down