diff --git a/homeassistant/components/datetime/__init__.py b/homeassistant/components/datetime/__init__.py index fb67f4b1ffb..b04008672ae 100644 --- a/homeassistant/components/datetime/__init__.py +++ b/homeassistant/components/datetime/__init__.py @@ -2,7 +2,7 @@ from __future__ import annotations from dataclasses import dataclass -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta import logging from typing import final @@ -110,7 +110,7 @@ class DateTimeEntity(Entity): "which is missing timezone information" ) - return value.astimezone(timezone.utc).isoformat(timespec="seconds") + return value.astimezone(UTC).isoformat(timespec="seconds") @property def native_value(self) -> datetime | None: diff --git a/homeassistant/components/demo/datetime.py b/homeassistant/components/demo/datetime.py index e7f72b66a87..63c8a5a7873 100644 --- a/homeassistant/components/demo/datetime.py +++ b/homeassistant/components/demo/datetime.py @@ -1,7 +1,7 @@ """Demo platform that offers a fake date/time entity.""" from __future__ import annotations -from datetime import datetime, timezone +from datetime import UTC, datetime from homeassistant.components.datetime import DateTimeEntity from homeassistant.config_entries import ConfigEntry @@ -23,7 +23,7 @@ async def async_setup_entry( DemoDateTime( "datetime", "Date and Time", - datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc), + datetime(2020, 1, 1, 12, 0, 0, tzinfo=UTC), "mdi:calendar-clock", False, ), diff --git a/homeassistant/components/gardena_bluetooth/sensor.py b/homeassistant/components/gardena_bluetooth/sensor.py index ebc83ae88af..dd2bde43cc4 100644 --- a/homeassistant/components/gardena_bluetooth/sensor.py +++ b/homeassistant/components/gardena_bluetooth/sensor.py @@ -2,7 +2,7 @@ from __future__ import annotations from dataclasses import dataclass, field -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta from gardena_bluetooth.const import Battery, Valve from gardena_bluetooth.parse import Characteristic @@ -106,7 +106,7 @@ class GardenaBluetoothRemainSensor(GardenaBluetoothEntity, SensorEntity): super()._handle_coordinator_update() return - time = datetime.now(timezone.utc) + timedelta(seconds=value) + time = datetime.now(UTC) + timedelta(seconds=value) if not self._attr_native_value: self._attr_native_value = time super()._handle_coordinator_update() diff --git a/homeassistant/components/google_mail/sensor.py b/homeassistant/components/google_mail/sensor.py index a65e845095c..dc1ee33c16e 100644 --- a/homeassistant/components/google_mail/sensor.py +++ b/homeassistant/components/google_mail/sensor.py @@ -1,7 +1,7 @@ """Support for Google Mail Sensors.""" from __future__ import annotations -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta from googleapiclient.http import HttpRequest @@ -46,7 +46,7 @@ class GoogleMailSensor(GoogleMailEntity, SensorEntity): data: dict = await self.hass.async_add_executor_job(settings.execute) if data["enableAutoReply"] and (end := data.get("endTime")): - value = datetime.fromtimestamp(int(end) / 1000, tz=timezone.utc) + value = datetime.fromtimestamp(int(end) / 1000, tz=UTC) else: value = None self._attr_native_value = value diff --git a/homeassistant/components/radarr/sensor.py b/homeassistant/components/radarr/sensor.py index 367e302d56f..803b6de44a4 100644 --- a/homeassistant/components/radarr/sensor.py +++ b/homeassistant/components/radarr/sensor.py @@ -4,7 +4,7 @@ from __future__ import annotations from collections.abc import Callable from copy import deepcopy from dataclasses import dataclass -from datetime import datetime, timezone +from datetime import UTC, datetime from typing import Any, Generic from aiopyarr import Diskspace, RootFolder, SystemStatus @@ -88,7 +88,7 @@ SENSOR_TYPES: dict[str, RadarrSensorEntityDescription[Any]] = { device_class=SensorDeviceClass.TIMESTAMP, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, - value_fn=lambda data, _: data.startTime.replace(tzinfo=timezone.utc), + value_fn=lambda data, _: data.startTime.replace(tzinfo=UTC), ), } diff --git a/homeassistant/components/sensor/__init__.py b/homeassistant/components/sensor/__init__.py index cbdaa24ec83..c00d20d51ef 100644 --- a/homeassistant/components/sensor/__init__.py +++ b/homeassistant/components/sensor/__init__.py @@ -5,12 +5,10 @@ import asyncio from collections.abc import Mapping from contextlib import suppress from dataclasses import dataclass -from datetime import date, datetime, timedelta, timezone +from datetime import UTC, date, datetime, timedelta from decimal import Decimal, InvalidOperation as DecimalInvalidOperation import logging from math import ceil, floor, log10 -import re -import sys from typing import Any, Final, Self, cast, final from homeassistant.config_entries import ConfigEntry @@ -89,10 +87,6 @@ _LOGGER: Final = logging.getLogger(__name__) ENTITY_ID_FORMAT: Final = DOMAIN + ".{}" -NEGATIVE_ZERO_PATTERN = re.compile(r"^-(0\.?0*)$") - -PY_311 = sys.version_info >= (3, 11, 0) - SCAN_INTERVAL: Final = timedelta(seconds=30) __all__ = [ @@ -534,8 +528,8 @@ class SensorEntity(Entity): "which is missing timezone information" ) - if value.tzinfo != timezone.utc: - value = value.astimezone(timezone.utc) + if value.tzinfo != UTC: + value = value.astimezone(UTC) return value.isoformat(timespec="seconds") except (AttributeError, OverflowError, TypeError) as err: @@ -636,12 +630,7 @@ class SensorEntity(Entity): ) precision = precision + floor(ratio_log) - if PY_311: - value = f"{converted_numerical_value:z.{precision}f}" - else: - value = f"{converted_numerical_value:.{precision}f}" - if value.startswith("-0") and NEGATIVE_ZERO_PATTERN.match(value): - value = value[1:] + value = f"{converted_numerical_value:z.{precision}f}" else: value = converted_numerical_value @@ -903,11 +892,6 @@ def async_rounded_state(hass: HomeAssistant, entity_id: str, state: State) -> st with suppress(TypeError, ValueError): numerical_value = float(value) - if PY_311: - value = f"{numerical_value:z.{precision}f}" - else: - value = f"{numerical_value:.{precision}f}" - if value.startswith("-0") and NEGATIVE_ZERO_PATTERN.match(value): - value = value[1:] + value = f"{numerical_value:z.{precision}f}" return value diff --git a/homeassistant/components/system_bridge/sensor.py b/homeassistant/components/system_bridge/sensor.py index 9290ebeacd5..4e0cbb9d2b9 100644 --- a/homeassistant/components/system_bridge/sensor.py +++ b/homeassistant/components/system_bridge/sensor.py @@ -3,7 +3,7 @@ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta from typing import Final, cast from homeassistant.components.sensor import ( @@ -146,9 +146,7 @@ BASE_SENSOR_TYPES: tuple[SystemBridgeSensorEntityDescription, ...] = ( name="Boot time", device_class=SensorDeviceClass.TIMESTAMP, icon="mdi:av-timer", - value=lambda data: datetime.fromtimestamp( - data.system.boot_time, tz=timezone.utc - ), + value=lambda data: datetime.fromtimestamp(data.system.boot_time, tz=UTC), ), SystemBridgeSensorEntityDescription( key="cpu_power_package", diff --git a/homeassistant/components/whois/sensor.py b/homeassistant/components/whois/sensor.py index 5163e0b3a6e..72c366bb0bc 100644 --- a/homeassistant/components/whois/sensor.py +++ b/homeassistant/components/whois/sensor.py @@ -3,7 +3,7 @@ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass -from datetime import datetime, timezone +from datetime import UTC, datetime from typing import cast from whois import Domain @@ -55,7 +55,7 @@ def _ensure_timezone(timestamp: datetime | None) -> datetime | None: # If timezone info isn't provided by the Whois, assume UTC. if timestamp.tzinfo is None: - return timestamp.replace(tzinfo=timezone.utc) + return timestamp.replace(tzinfo=UTC) return timestamp diff --git a/homeassistant/components/zha/sensor.py b/homeassistant/components/zha/sensor.py index 0e520d98b52..c514e02ec57 100644 --- a/homeassistant/components/zha/sensor.py +++ b/homeassistant/components/zha/sensor.py @@ -4,7 +4,6 @@ from __future__ import annotations import enum import functools import numbers -import sys from typing import TYPE_CHECKING, Any, Self from zigpy import types @@ -485,7 +484,7 @@ class SmartEnergyMetering(Sensor): if self._cluster_handler.device_type is not None: attrs["device_type"] = self._cluster_handler.device_type if (status := self._cluster_handler.status) is not None: - if isinstance(status, enum.IntFlag) and sys.version_info >= (3, 11): + if isinstance(status, enum.IntFlag): attrs["status"] = str( status.name if status.name is not None else status.value ) diff --git a/homeassistant/util/async_.py b/homeassistant/util/async_.py index 4caf074b879..ce1105cff75 100644 --- a/homeassistant/util/async_.py +++ b/homeassistant/util/async_.py @@ -21,9 +21,7 @@ _P = ParamSpec("_P") def cancelling(task: Future[Any]) -> bool: - """Return True if task is done or cancelling.""" - # https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancelling - # is new in Python 3.11 + """Return True if task is cancelling.""" return bool((cancelling_ := getattr(task, "cancelling", None)) and cancelling_()) diff --git a/homeassistant/util/dt.py b/homeassistant/util/dt.py index 4f49ec44ca7..34a81728d14 100644 --- a/homeassistant/util/dt.py +++ b/homeassistant/util/dt.py @@ -14,8 +14,8 @@ import zoneinfo import ciso8601 DATE_STR_FORMAT = "%Y-%m-%d" -UTC = dt.timezone.utc -DEFAULT_TIME_ZONE: dt.tzinfo = dt.timezone.utc +UTC = dt.UTC +DEFAULT_TIME_ZONE: dt.tzinfo = dt.UTC CLOCK_MONOTONIC_COARSE = 6 # EPOCHORDINAL is not exposed as a constant diff --git a/pyproject.toml b/pyproject.toml index fcc47ed2c31..3c0ea4c4e34 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -521,8 +521,6 @@ filterwarnings = [ ] [tool.ruff] -target-version = "py310" - select = [ "B002", # Python does not support the unary prefix increment "B007", # Loop control variable {name} not used within loop body diff --git a/script/gen_requirements_all.py b/script/gen_requirements_all.py index 5a683660efe..101a57e419d 100755 --- a/script/gen_requirements_all.py +++ b/script/gen_requirements_all.py @@ -9,9 +9,8 @@ from pathlib import Path import pkgutil import re import sys -from typing import Any - import tomllib +from typing import Any from homeassistant.util.yaml.loader import load_yaml from script.hassfest.model import Integration diff --git a/tests/common.py b/tests/common.py index 6f2209276ce..df8722a563c 100644 --- a/tests/common.py +++ b/tests/common.py @@ -5,7 +5,7 @@ import asyncio from collections import OrderedDict from collections.abc import Generator, Mapping, Sequence from contextlib import contextmanager -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta import functools as ft from functools import lru_cache from io import StringIO @@ -384,7 +384,7 @@ def async_fire_time_changed_exact( approach, as this is only for testing. """ if datetime_ is None: - utc_datetime = datetime.now(timezone.utc) + utc_datetime = datetime.now(UTC) else: utc_datetime = dt_util.as_utc(datetime_) @@ -406,7 +406,7 @@ def async_fire_time_changed( for an exact microsecond, use async_fire_time_changed_exact. """ if datetime_ is None: - utc_datetime = datetime.now(timezone.utc) + utc_datetime = datetime.now(UTC) else: utc_datetime = dt_util.as_utc(datetime_) diff --git a/tests/components/datetime/test_init.py b/tests/components/datetime/test_init.py index 66390c8d90f..6f2e2db29a1 100644 --- a/tests/components/datetime/test_init.py +++ b/tests/components/datetime/test_init.py @@ -1,5 +1,5 @@ """The tests for the datetime component.""" -from datetime import datetime, timezone +from datetime import UTC, datetime from zoneinfo import ZoneInfo import pytest @@ -14,7 +14,7 @@ from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_PLATFOR from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component -DEFAULT_VALUE = datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc) +DEFAULT_VALUE = datetime(2020, 1, 1, 12, 0, 0, tzinfo=UTC) class MockDateTimeEntity(DateTimeEntity): diff --git a/tests/components/environment_canada/test_diagnostics.py b/tests/components/environment_canada/test_diagnostics.py index f85de2cb97c..6044c9e778b 100644 --- a/tests/components/environment_canada/test_diagnostics.py +++ b/tests/components/environment_canada/test_diagnostics.py @@ -1,5 +1,5 @@ """Test Environment Canada diagnostics.""" -from datetime import datetime, timezone +from datetime import UTC, datetime import json from unittest.mock import AsyncMock, MagicMock, patch @@ -43,7 +43,7 @@ async def init_integration(hass: HomeAssistant) -> MockConfigEntry: ) weather_mock = mock_ec() - ec_data["metadata"]["timestamp"] = datetime(2022, 10, 4, tzinfo=timezone.utc) + ec_data["metadata"]["timestamp"] = datetime(2022, 10, 4, tzinfo=UTC) weather_mock.conditions = ec_data["conditions"] weather_mock.alerts = ec_data["alerts"] weather_mock.daily_forecasts = ec_data["daily_forecasts"] @@ -51,7 +51,7 @@ async def init_integration(hass: HomeAssistant) -> MockConfigEntry: radar_mock = mock_ec() radar_mock.image = b"GIF..." - radar_mock.timestamp = datetime(2022, 10, 4, tzinfo=timezone.utc) + radar_mock.timestamp = datetime(2022, 10, 4, tzinfo=UTC) with patch( "homeassistant.components.environment_canada.ECWeather", diff --git a/tests/components/forecast_solar/test_energy.py b/tests/components/forecast_solar/test_energy.py index 3ca89d33faa..7d3a853b8a7 100644 --- a/tests/components/forecast_solar/test_energy.py +++ b/tests/components/forecast_solar/test_energy.py @@ -1,5 +1,5 @@ """Test forecast solar energy platform.""" -from datetime import datetime, timezone +from datetime import UTC, datetime from unittest.mock import MagicMock from homeassistant.components.forecast_solar import energy @@ -16,8 +16,8 @@ async def test_energy_solar_forecast( ) -> None: """Test the Forecast.Solar energy platform solar forecast.""" mock_forecast_solar.estimate.return_value.wh_period = { - datetime(2021, 6, 27, 13, 0, tzinfo=timezone.utc): 12, - datetime(2021, 6, 27, 14, 0, tzinfo=timezone.utc): 8, + datetime(2021, 6, 27, 13, 0, tzinfo=UTC): 12, + datetime(2021, 6, 27, 14, 0, tzinfo=UTC): 8, } mock_config_entry.add_to_hass(hass) diff --git a/tests/components/google_assistant/test_http.py b/tests/components/google_assistant/test_http.py index b7dc880ede0..44dc40f5a47 100644 --- a/tests/components/google_assistant/test_http.py +++ b/tests/components/google_assistant/test_http.py @@ -1,5 +1,5 @@ """Test Google http services.""" -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta from http import HTTPStatus from typing import Any from unittest.mock import ANY, patch @@ -51,7 +51,7 @@ async def test_get_jwt(hass: HomeAssistant) -> None: jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkdW1teUBkdW1teS5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIsInNjb3BlIjoiaHR0cHM6Ly93d3cuZ29vZ2xlYXBpcy5jb20vYXV0aC9ob21lZ3JhcGgiLCJhdWQiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20vby9vYXV0aDIvdG9rZW4iLCJpYXQiOjE1NzEwMTEyMDAsImV4cCI6MTU3MTAxNDgwMH0.akHbMhOflXdIDHVvUVwO0AoJONVOPUdCghN6hAdVz4gxjarrQeGYc_Qn2r84bEvCU7t6EvimKKr0fyupyzBAzfvKULs5mTHO3h2CwSgvOBMv8LnILboJmbO4JcgdnRV7d9G3ktQs7wWSCXJsI5i5jUr1Wfi9zWwxn2ebaAAgrp8" res = _get_homegraph_jwt( - datetime(2019, 10, 14, tzinfo=timezone.utc), + datetime(2019, 10, 14, tzinfo=UTC), DUMMY_CONFIG["service_account"]["client_email"], DUMMY_CONFIG["service_account"]["private_key"], ) @@ -85,7 +85,7 @@ async def test_update_access_token(hass: HomeAssistant) -> None: config = GoogleConfig(hass, DUMMY_CONFIG) await config.async_initialize() - base_time = datetime(2019, 10, 14, tzinfo=timezone.utc) + base_time = datetime(2019, 10, 14, tzinfo=UTC) with patch( "homeassistant.components.google_assistant.http._get_homegraph_token" ) as mock_get_token, patch( diff --git a/tests/components/home_plus_control/test_switch.py b/tests/components/home_plus_control/test_switch.py index ead1f83cb94..d41977d57a9 100644 --- a/tests/components/home_plus_control/test_switch.py +++ b/tests/components/home_plus_control/test_switch.py @@ -143,7 +143,7 @@ async def test_plant_topology_reduction_change( return_value=mock_modules, ) as mock_check: async_fire_time_changed( - hass, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=400) + hass, dt.datetime.now(dt.UTC) + dt.timedelta(seconds=400) ) await hass.async_block_till_done() assert len(mock_check.mock_calls) == 1 @@ -205,7 +205,7 @@ async def test_plant_topology_increase_change( return_value=mock_modules, ) as mock_check: async_fire_time_changed( - hass, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=400) + hass, dt.datetime.now(dt.UTC) + dt.timedelta(seconds=400) ) await hass.async_block_till_done() assert len(mock_check.mock_calls) == 1 @@ -267,7 +267,7 @@ async def test_module_status_unavailable( return_value=mock_modules, ) as mock_check: async_fire_time_changed( - hass, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=400) + hass, dt.datetime.now(dt.UTC) + dt.timedelta(seconds=400) ) await hass.async_block_till_done() assert len(mock_check.mock_calls) == 1 @@ -338,7 +338,7 @@ async def test_module_status_available( return_value=mock_modules, ) as mock_check: async_fire_time_changed( - hass, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=400) + hass, dt.datetime.now(dt.UTC) + dt.timedelta(seconds=400) ) await hass.async_block_till_done() assert len(mock_check.mock_calls) == 1 @@ -442,7 +442,7 @@ async def test_update_with_api_error( side_effect=HomePlusControlApiError, ) as mock_check: async_fire_time_changed( - hass, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=400) + hass, dt.datetime.now(dt.UTC) + dt.timedelta(seconds=400) ) await hass.async_block_till_done() assert len(mock_check.mock_calls) == 1 diff --git a/tests/components/ipma/__init__.py b/tests/components/ipma/__init__.py index ba172fc7bb8..827481c60de 100644 --- a/tests/components/ipma/__init__.py +++ b/tests/components/ipma/__init__.py @@ -1,6 +1,6 @@ """Tests for the IPMA component.""" from collections import namedtuple -from datetime import datetime, timezone +from datetime import UTC, datetime from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_MODE, CONF_NAME @@ -87,7 +87,7 @@ class MockLocation: return [ Forecast( "7.7", - datetime(2020, 1, 15, 1, 0, 0, tzinfo=timezone.utc), + datetime(2020, 1, 15, 1, 0, 0, tzinfo=UTC), 1, "86.9", 12.0, @@ -101,7 +101,7 @@ class MockLocation: ), Forecast( "5.7", - datetime(2020, 1, 15, 2, 0, 0, tzinfo=timezone.utc), + datetime(2020, 1, 15, 2, 0, 0, tzinfo=UTC), 1, "86.9", 12.0, diff --git a/tests/components/melnor/conftest.py b/tests/components/melnor/conftest.py index ab51bf44a57..3e87a4e646f 100644 --- a/tests/components/melnor/conftest.py +++ b/tests/components/melnor/conftest.py @@ -2,7 +2,7 @@ from __future__ import annotations from collections.abc import Generator -from datetime import datetime, time, timedelta, timezone +from datetime import UTC, datetime, time, timedelta from unittest.mock import AsyncMock, patch from melnor_bluetooth.device import Device @@ -73,7 +73,7 @@ class MockFrequency: self._interval = 0 self._is_watering = False self._start_time = time(12, 0) - self._next_run_time = datetime(2021, 1, 1, 12, 0, tzinfo=timezone.utc) + self._next_run_time = datetime(2021, 1, 1, 12, 0, tzinfo=UTC) @property def duration_minutes(self) -> int: diff --git a/tests/components/octoprint/test_sensor.py b/tests/components/octoprint/test_sensor.py index a388aeae106..2ba657c77d5 100644 --- a/tests/components/octoprint/test_sensor.py +++ b/tests/components/octoprint/test_sensor.py @@ -1,5 +1,5 @@ """The tests for Octoptint binary sensor module.""" -from datetime import datetime, timezone +from datetime import UTC, datetime from unittest.mock import patch from homeassistant.core import HomeAssistant @@ -24,7 +24,7 @@ async def test_sensors(hass: HomeAssistant) -> None: } with patch( "homeassistant.util.dt.utcnow", - return_value=datetime(2020, 2, 20, 9, 10, 13, 543, tzinfo=timezone.utc), + return_value=datetime(2020, 2, 20, 9, 10, 13, 543, tzinfo=UTC), ): await init_integration(hass, "sensor", printer=printer, job=job) diff --git a/tests/components/prusalink/test_sensor.py b/tests/components/prusalink/test_sensor.py index 6a0944bdf36..0f2a966b4e4 100644 --- a/tests/components/prusalink/test_sensor.py +++ b/tests/components/prusalink/test_sensor.py @@ -1,6 +1,6 @@ """Test Prusalink sensors.""" -from datetime import datetime, timezone +from datetime import UTC, datetime from unittest.mock import PropertyMock, patch import pytest @@ -125,7 +125,7 @@ async def test_sensors_active_job( """Test sensors while active job.""" with patch( "homeassistant.components.prusalink.sensor.utcnow", - return_value=datetime(2022, 8, 27, 14, 0, 0, tzinfo=timezone.utc), + return_value=datetime(2022, 8, 27, 14, 0, 0, tzinfo=UTC), ): assert await async_setup_component(hass, "prusalink", {}) diff --git a/tests/components/recorder/test_util.py b/tests/components/recorder/test_util.py index ecfd188db8e..a7b15a7f12d 100644 --- a/tests/components/recorder/test_util.py +++ b/tests/components/recorder/test_util.py @@ -1,6 +1,6 @@ """Test util methods.""" from collections.abc import Callable -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta import os from pathlib import Path import sqlite3 @@ -948,7 +948,7 @@ def test_execute_stmt_lambda_element( assert rows == ["mock_row"] -@pytest.mark.freeze_time(datetime(2022, 10, 21, 7, 25, tzinfo=timezone.utc)) +@pytest.mark.freeze_time(datetime(2022, 10, 21, 7, 25, tzinfo=UTC)) async def test_resolve_period(hass: HomeAssistant) -> None: """Test statistic_during_period.""" diff --git a/tests/components/sensor/test_init.py b/tests/components/sensor/test_init.py index c5406a85fc0..530e8cb4209 100644 --- a/tests/components/sensor/test_init.py +++ b/tests/components/sensor/test_init.py @@ -2,7 +2,7 @@ from __future__ import annotations from collections.abc import Generator -from datetime import date, datetime, timezone +from datetime import UTC, date, datetime from decimal import Decimal from typing import Any @@ -177,7 +177,7 @@ async def test_datetime_conversion( enable_custom_integrations: None, ) -> None: """Test conversion of datetime.""" - test_timestamp = datetime(2017, 12, 19, 18, 29, 42, tzinfo=timezone.utc) + test_timestamp = datetime(2017, 12, 19, 18, 29, 42, tzinfo=UTC) test_local_timestamp = test_timestamp.astimezone( dt_util.get_time_zone("Europe/Amsterdam") ) @@ -233,7 +233,7 @@ async def test_a_sensor_with_a_non_numeric_device_class( A non numeric sensor with a valid device class should never be handled as numeric because it has a device class. """ - test_timestamp = datetime(2017, 12, 19, 18, 29, 42, tzinfo=timezone.utc) + test_timestamp = datetime(2017, 12, 19, 18, 29, 42, tzinfo=UTC) test_local_timestamp = test_timestamp.astimezone( dt_util.get_time_zone("Europe/Amsterdam") ) @@ -334,7 +334,7 @@ RESTORE_DATA = { "native_unit_of_measurement": None, "native_value": { "__type": "", - "isoformat": datetime(2020, 2, 8, 15, tzinfo=timezone.utc).isoformat(), + "isoformat": datetime(2020, 2, 8, 15, tzinfo=UTC).isoformat(), }, }, "Decimal": { @@ -375,7 +375,7 @@ RESTORE_DATA = { ), (date(2020, 2, 8), dict, RESTORE_DATA["date"], SensorDeviceClass.DATE, None), ( - datetime(2020, 2, 8, 15, tzinfo=timezone.utc), + datetime(2020, 2, 8, 15, tzinfo=UTC), dict, RESTORE_DATA["datetime"], SensorDeviceClass.TIMESTAMP, @@ -433,7 +433,7 @@ async def test_restore_sensor_save_state( (123.0, float, RESTORE_DATA["float"], SensorDeviceClass.TEMPERATURE, "°F"), (date(2020, 2, 8), date, RESTORE_DATA["date"], SensorDeviceClass.DATE, None), ( - datetime(2020, 2, 8, 15, tzinfo=timezone.utc), + datetime(2020, 2, 8, 15, tzinfo=UTC), datetime, RESTORE_DATA["datetime"], SensorDeviceClass.TIMESTAMP, diff --git a/tests/components/subaru/api_responses.py b/tests/components/subaru/api_responses.py index e2fdf9ae508..52c57e7348a 100644 --- a/tests/components/subaru/api_responses.py +++ b/tests/components/subaru/api_responses.py @@ -1,6 +1,6 @@ """Sample API response data for tests.""" -from datetime import datetime, timezone +from datetime import UTC, datetime from homeassistant.components.subaru.const import ( API_GEN_1, @@ -58,7 +58,7 @@ VEHICLE_DATA = { }, } -MOCK_DATETIME = datetime.fromtimestamp(1595560000, timezone.utc) +MOCK_DATETIME = datetime.fromtimestamp(1595560000, UTC) VEHICLE_STATUS_EV = { VEHICLE_STATUS: { diff --git a/tests/components/template/test_binary_sensor.py b/tests/components/template/test_binary_sensor.py index 1e6b2cc3840..e43163f66fc 100644 --- a/tests/components/template/test_binary_sensor.py +++ b/tests/components/template/test_binary_sensor.py @@ -1,5 +1,5 @@ """The tests for the Template Binary sensor platform.""" -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta import logging from unittest.mock import patch @@ -1276,9 +1276,7 @@ async def test_trigger_entity_restore_state_auto_off( fake_extra_data = { "auto_off_time": { "__type": "", - "isoformat": datetime( - 2022, 2, 2, 12, 2, 2, tzinfo=timezone.utc - ).isoformat(), + "isoformat": datetime(2022, 2, 2, 12, 2, 2, tzinfo=UTC).isoformat(), }, } mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data),)) @@ -1336,9 +1334,7 @@ async def test_trigger_entity_restore_state_auto_off_expired( fake_extra_data = { "auto_off_time": { "__type": "", - "isoformat": datetime( - 2022, 2, 2, 12, 2, 0, tzinfo=timezone.utc - ).isoformat(), + "isoformat": datetime(2022, 2, 2, 12, 2, 0, tzinfo=UTC).isoformat(), }, } mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data),)) diff --git a/tests/components/template/test_button.py b/tests/components/template/test_button.py index f3fd3e03ce0..bfdb9352767 100644 --- a/tests/components/template/test_button.py +++ b/tests/components/template/test_button.py @@ -97,7 +97,7 @@ async def test_all_optional_config(hass: HomeAssistant, calls) -> None: _TEST_OPTIONS_BUTTON, ) - now = dt.datetime.now(dt.timezone.utc) + now = dt.datetime.now(dt.UTC) with patch("homeassistant.util.dt.utcnow", return_value=now): await hass.services.async_call( diff --git a/tests/components/uvc/test_camera.py b/tests/components/uvc/test_camera.py index 0c532d9007d..dd42cfc2977 100644 --- a/tests/components/uvc/test_camera.py +++ b/tests/components/uvc/test_camera.py @@ -1,5 +1,5 @@ """The tests for UVC camera module.""" -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta from unittest.mock import call, patch import pytest @@ -368,7 +368,7 @@ async def test_motion_recording_mode_properties( assert state assert state.state != STATE_RECORDING assert state.attributes["last_recording_start_time"] == datetime( - 2021, 1, 8, 1, 56, 32, 367000, tzinfo=timezone.utc + 2021, 1, 8, 1, 56, 32, 367000, tzinfo=UTC ) mock_remote.return_value.get_camera.return_value["recordingIndicator"] = "DISABLED" diff --git a/tests/components/whirlpool/test_sensor.py b/tests/components/whirlpool/test_sensor.py index 8e8c5513097..3155d588e14 100644 --- a/tests/components/whirlpool/test_sensor.py +++ b/tests/components/whirlpool/test_sensor.py @@ -1,5 +1,5 @@ """Test the Whirlpool Sensor domain.""" -from datetime import datetime, timezone +from datetime import UTC, datetime from unittest.mock import MagicMock import pytest @@ -50,7 +50,7 @@ async def test_dryer_sensor_values( ) -> None: """Test the sensor value callbacks.""" hass.state = CoreState.not_running - thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, timezone.utc) + thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, UTC) mock_restore_cache_with_extra_data( hass, ( @@ -114,7 +114,7 @@ async def test_washer_sensor_values( ) -> None: """Test the sensor value callbacks.""" hass.state = CoreState.not_running - thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, timezone.utc) + thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, UTC) mock_restore_cache_with_extra_data( hass, ( @@ -281,7 +281,7 @@ async def test_restore_state( """Test sensor restore state.""" # Home assistant is not running yet hass.state = CoreState.not_running - thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, timezone.utc) + thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, UTC) mock_restore_cache_with_extra_data( hass, ( @@ -334,7 +334,7 @@ async def test_callback( ) -> None: """Test callback timestamp callback function.""" hass.state = CoreState.not_running - thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, timezone.utc) + thetimestamp: datetime = datetime(2022, 11, 29, 00, 00, 00, 00, UTC) mock_restore_cache_with_extra_data( hass, ( diff --git a/tests/testing_config/custom_components/test/datetime.py b/tests/testing_config/custom_components/test/datetime.py index 7fca8d57881..ba511e81648 100644 --- a/tests/testing_config/custom_components/test/datetime.py +++ b/tests/testing_config/custom_components/test/datetime.py @@ -2,7 +2,7 @@ Call init before using it in your tests to ensure clean test data. """ -from datetime import datetime, timezone +from datetime import UTC, datetime from homeassistant.components.datetime import DateTimeEntity @@ -37,7 +37,7 @@ def init(empty=False): MockDateTimeEntity( name="test", unique_id=UNIQUE_DATETIME, - native_value=datetime(2020, 1, 1, 1, 2, 3, tzinfo=timezone.utc), + native_value=datetime(2020, 1, 1, 1, 2, 3, tzinfo=UTC), ), ] )