Skip to content

Commit

Permalink
Import util.dt as dt_util in components/[t-z]* (#93763)
Browse files Browse the repository at this point in the history
  • Loading branch information
scop committed May 29, 2023
1 parent 70c4982 commit 1ce74ba
Show file tree
Hide file tree
Showing 25 changed files with 134 additions and 119 deletions.
30 changes: 15 additions & 15 deletions homeassistant/components/todoist/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .const import (
ALL_DAY,
Expand Down Expand Up @@ -214,14 +214,14 @@ async def handle_new_task(call: ServiceCall) -> None:
data["due_lang"] = call.data[DUE_DATE_LANG]

if DUE_DATE in call.data:
due_date = dt.parse_datetime(call.data[DUE_DATE])
due_date = dt_util.parse_datetime(call.data[DUE_DATE])
if due_date is None:
due = dt.parse_date(call.data[DUE_DATE])
due = dt_util.parse_date(call.data[DUE_DATE])
if due is None:
raise ValueError(f"Invalid due_date: {call.data[DUE_DATE]}")
due_date = datetime(due.year, due.month, due.day)
# Format it in the manner Todoist expects
due_date = dt.as_utc(due_date)
due_date = dt_util.as_utc(due_date)
date_format = "%Y-%m-%dT%H:%M:%S"
data["due_datetime"] = datetime.strftime(due_date, date_format)

Expand All @@ -239,16 +239,16 @@ async def handle_new_task(call: ServiceCall) -> None:
_reminder_due["lang"] = call.data[REMINDER_DATE_LANG]

if REMINDER_DATE in call.data:
due_date = dt.parse_datetime(call.data[REMINDER_DATE])
due_date = dt_util.parse_datetime(call.data[REMINDER_DATE])
if due_date is None:
due = dt.parse_date(call.data[REMINDER_DATE])
due = dt_util.parse_date(call.data[REMINDER_DATE])
if due is None:
raise ValueError(
f"Invalid reminder_date: {call.data[REMINDER_DATE]}"
)
due_date = datetime(due.year, due.month, due.day)
# Format it in the manner Todoist expects
due_date = dt.as_utc(due_date)
due_date = dt_util.as_utc(due_date)
date_format = "%Y-%m-%dT%H:%M:%S"
_reminder_due["date"] = datetime.strftime(due_date, date_format)

Expand Down Expand Up @@ -453,7 +453,7 @@ def create_todoist_task(self, data: Task):
LABELS: [],
OVERDUE: False,
PRIORITY: data.priority,
START: dt.now(),
START: dt_util.now(),
SUMMARY: data.content,
}

Expand All @@ -474,19 +474,19 @@ def create_todoist_task(self, data: Task):
# complete the task.
# Generally speaking, that means right now.
if data.due is not None:
end = dt.parse_datetime(
end = dt_util.parse_datetime(
data.due.datetime if data.due.datetime else data.due.date
)
task[END] = dt.as_local(end) if end is not None else end
task[END] = dt_util.as_local(end) if end is not None else end
if task[END] is not None:
if self._due_date_days is not None and (
task[END] > dt.now() + self._due_date_days
task[END] > dt_util.now() + self._due_date_days
):
# This task is out of range of our due date;
# it shouldn't be counted.
return None

task[DUE_TODAY] = task[END].date() == dt.now().date()
task[DUE_TODAY] = task[END].date() == dt_util.now().date()

# Special case: Task is overdue.
if task[END] <= task[START]:
Expand Down Expand Up @@ -669,10 +669,10 @@ def update(self) -> None:
def get_start(due: Due) -> datetime | date | None:
"""Return the task due date as a start date or date time."""
if due.datetime:
start = dt.parse_datetime(due.datetime)
start = dt_util.parse_datetime(due.datetime)
if not start:
return None
return dt.as_local(start)
return dt_util.as_local(start)
if due.date:
return dt.parse_date(due.date)
return dt_util.parse_date(due.date)
return None
12 changes: 7 additions & 5 deletions homeassistant/components/trafikverket_ferry/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .const import CONF_FROM, CONF_TIME, CONF_TO, DOMAIN

Expand Down Expand Up @@ -60,20 +60,22 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
)
self._from: str = entry.data[CONF_FROM]
self._to: str = entry.data[CONF_TO]
self._time: time | None = dt.parse_time(entry.data[CONF_TIME])
self._time: time | None = dt_util.parse_time(entry.data[CONF_TIME])
self._weekdays: list[str] = entry.data[CONF_WEEKDAY]

async def _async_update_data(self) -> dict[str, Any]:
"""Fetch data from Trafikverket."""

departure_day = next_departuredate(self._weekdays)
current_time = dt.now()
current_time = dt_util.now()
when = (
datetime.combine(
departure_day, self._time, dt.get_time_zone(self.hass.config.time_zone)
departure_day,
self._time,
dt_util.get_time_zone(self.hass.config.time_zone),
)
if self._time
else dt.now()
else dt_util.now()
)
if current_time > when:
when = current_time
Expand Down
18 changes: 10 additions & 8 deletions homeassistant/components/trafikverket_train/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .const import CONF_FROM, CONF_TIME, CONF_TO, DOMAIN
from .util import create_unique_id
Expand Down Expand Up @@ -48,7 +48,7 @@ async def async_setup_entry(
to_station = hass.data[DOMAIN][entry.entry_id][CONF_TO]
from_station = hass.data[DOMAIN][entry.entry_id][CONF_FROM]
get_time: str | None = entry.data.get(CONF_TIME)
train_time = dt.parse_time(get_time) if get_time else None
train_time = dt_util.parse_time(get_time) if get_time else None

async_add_entities(
[
Expand Down Expand Up @@ -89,7 +89,7 @@ def next_departuredate(departure: list[str]) -> date:

def _to_iso_format(traintime: datetime) -> str:
"""Return isoformatted utc time."""
return dt.as_utc(traintime).isoformat()
return dt_util.as_utc(traintime).isoformat()


class TrainSensor(SensorEntity):
Expand Down Expand Up @@ -131,12 +131,14 @@ def __init__(

async def async_update(self) -> None:
"""Retrieve latest state."""
when = dt.now()
when = dt_util.now()
_state: TrainStop | None = None
if self._time:
departure_day = next_departuredate(self._weekday)
when = datetime.combine(
departure_day, self._time, dt.get_time_zone(self.hass.config.time_zone)
departure_day,
self._time,
dt_util.get_time_zone(self.hass.config.time_zone),
)
try:
if self._time:
Expand All @@ -162,11 +164,11 @@ async def async_update(self) -> None:
# The original datetime doesn't provide a timezone so therefore attaching it here.
if TYPE_CHECKING:
assert _state.advertised_time_at_location
self._attr_native_value = dt.as_utc(_state.advertised_time_at_location)
self._attr_native_value = dt_util.as_utc(_state.advertised_time_at_location)
if _state.time_at_location:
self._attr_native_value = dt.as_utc(_state.time_at_location)
self._attr_native_value = dt_util.as_utc(_state.time_at_location)
if _state.estimated_time_at_location:
self._attr_native_value = dt.as_utc(_state.estimated_time_at_location)
self._attr_native_value = dt_util.as_utc(_state.estimated_time_at_location)

self._update_attributes(_state)

Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/vallox/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from . import ValloxDataUpdateCoordinator, ValloxEntity
from .const import (
Expand Down Expand Up @@ -108,7 +108,7 @@ def native_value(self) -> StateType | datetime:

return datetime.combine(
next_filter_change_date,
time(hour=13, minute=0, second=0, tzinfo=dt.DEFAULT_TIME_ZONE),
time(hour=13, minute=0, second=0, tzinfo=dt_util.DEFAULT_TIME_ZONE),
)


Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/withings/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
)
from homeassistant.helpers.entity import Entity, EntityDescription
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from . import const
from .const import Measurement
Expand Down Expand Up @@ -411,7 +411,7 @@ async def _async_get_all_data(self) -> dict[Measurement, Any] | None:
async def async_get_measures(self) -> dict[Measurement, Any]:
"""Get the measures data."""
_LOGGER.debug("Updating withings measures")
now = dt.utcnow()
now = dt_util.utcnow()
startdate = now - datetime.timedelta(days=7)

response = await self._hass.async_add_executor_job(
Expand Down Expand Up @@ -439,7 +439,7 @@ async def async_get_measures(self) -> dict[Measurement, Any]:
async def async_get_sleep_summary(self) -> dict[Measurement, Any]:
"""Get the sleep summary data."""
_LOGGER.debug("Updating withing sleep summary")
now = dt.utcnow()
now = dt_util.utcnow()
yesterday = now - datetime.timedelta(days=1)
yesterday_noon = datetime.datetime(
yesterday.year,
Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/workday/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .const import (
ALLOWED_DAYS,
Expand Down Expand Up @@ -120,7 +120,7 @@ async def async_setup_entry(
sensor_name: str = entry.options[CONF_NAME]
workdays: list[str] = entry.options[CONF_WORKDAYS]

year: int = (dt.now() + timedelta(days=days_offset)).year
year: int = (dt_util.now() + timedelta(days=days_offset)).year
obj_holidays: HolidayBase = getattr(holidays, country)(years=year)

if province:
Expand All @@ -140,7 +140,7 @@ async def async_setup_entry(
for remove_holiday in remove_holidays:
try:
# is this formatted as a date?
if dt.parse_date(remove_holiday):
if dt_util.parse_date(remove_holiday):
# remove holiday by date
removed = obj_holidays.pop(remove_holiday)
LOGGER.debug("Removed %s", remove_holiday)
Expand Down Expand Up @@ -231,7 +231,7 @@ async def async_update(self) -> None:
self._attr_is_on = False

# Get ISO day of the week (1 = Monday, 7 = Sunday)
adjusted_date = dt.now() + timedelta(days=self._days_offset)
adjusted_date = dt_util.now() + timedelta(days=self._days_offset)
day = adjusted_date.isoweekday() - 1
day_of_week = ALLOWED_DAYS[day]

Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/workday/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
SelectSelectorMode,
TextSelector,
)
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .const import (
ALLOWED_DAYS,
Expand Down Expand Up @@ -73,16 +73,16 @@ def validate_custom_dates(user_input: dict[str, Any]) -> None:
"""Validate custom dates for add/remove holidays."""

for add_date in user_input[CONF_ADD_HOLIDAYS]:
if dt.parse_date(add_date) is None:
if dt_util.parse_date(add_date) is None:
raise AddDatesError("Incorrect date")

year: int = dt.now().year
year: int = dt_util.now().year
obj_holidays = country_holidays(
user_input[CONF_COUNTRY], user_input.get(CONF_PROVINCE), year
)

for remove_date in user_input[CONF_REMOVE_HOLIDAYS]:
if dt.parse_date(remove_date) is None:
if dt_util.parse_date(remove_date) is None:
if obj_holidays.get_named(remove_date) == []:
raise RemoveDatesError("Incorrect date or name")

Expand Down
10 changes: 5 additions & 5 deletions homeassistant/components/xiaomi_miio/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import color, dt
from homeassistant.util import color, dt as dt_util

from .const import (
CONF_DEVICE,
Expand Down Expand Up @@ -362,7 +362,7 @@ async def async_update(self) -> None:

delayed_turn_off = self.delayed_turn_off_timestamp(
state.delay_off_countdown,
dt.utcnow(),
dt_util.utcnow(),
self._state_attrs[ATTR_DELAYED_TURN_OFF],
)

Expand Down Expand Up @@ -523,7 +523,7 @@ async def async_update(self) -> None:

delayed_turn_off = self.delayed_turn_off_timestamp(
state.delay_off_countdown,
dt.utcnow(),
dt_util.utcnow(),
self._state_attrs[ATTR_DELAYED_TURN_OFF],
)

Expand Down Expand Up @@ -582,7 +582,7 @@ async def async_update(self) -> None:

delayed_turn_off = self.delayed_turn_off_timestamp(
state.delay_off_countdown,
dt.utcnow(),
dt_util.utcnow(),
self._state_attrs[ATTR_DELAYED_TURN_OFF],
)

Expand Down Expand Up @@ -625,7 +625,7 @@ async def async_update(self) -> None:

delayed_turn_off = self.delayed_turn_off_timestamp(
state.delay_off_countdown,
dt.utcnow(),
dt_util.utcnow(),
self._state_attrs[ATTR_DELAYED_TURN_OFF],
)

Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/zha/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from homeassistant.data_entry_flow import FlowHandler, FlowResult
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.selector import FileSelector, FileSelectorConfig
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .core.const import (
CONF_BAUDRATE,
Expand Down Expand Up @@ -69,7 +69,7 @@ def _format_backup_choice(
) -> str:
"""Format network backup info into a short piece of text."""
if not pan_ids:
return dt.as_local(backup.backup_time).strftime("%c")
return dt_util.as_local(backup.backup_time).strftime("%c")

identifier = (
# PAN ID
Expand All @@ -78,7 +78,7 @@ def _format_backup_choice(
f":{str(backup.network_info.extended_pan_id).replace(':', '')}"
).lower()

return f"{dt.as_local(backup.backup_time).strftime('%c')} ({identifier})"
return f"{dt_util.as_local(backup.backup_time).strftime('%c')} ({identifier})"


async def list_serial_ports(hass: HomeAssistant) -> list[ListPortInfo]:
Expand Down
7 changes: 4 additions & 3 deletions tests/components/tasmota/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from homeassistant.const import ATTR_ASSUMED_STATE, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt
from homeassistant.util import dt as dt_util

from .test_common import (
DEFAULT_CONFIG,
Expand Down Expand Up @@ -727,7 +727,7 @@ async def test_restart_time_status_sensor_state_via_mqtt(
assert not state.attributes.get(ATTR_ASSUMED_STATE)

# Test polled state update
utc_now = datetime.datetime(2020, 11, 11, 8, 0, 0, tzinfo=dt.UTC)
utc_now = datetime.datetime(2020, 11, 11, 8, 0, 0, tzinfo=dt_util.UTC)
hatasmota.status_sensor.datetime.now.return_value = utc_now
async_fire_mqtt_message(
hass,
Expand Down Expand Up @@ -931,7 +931,8 @@ async def test_enable_status_sensor(

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

Expand Down

0 comments on commit 1ce74ba

Please sign in to comment.