Skip to content

Commit

Permalink
Add datetime object as valid StateType
Browse files Browse the repository at this point in the history
  • Loading branch information
frenck committed Jul 28, 2021
1 parent 1c20eb3 commit d4470af
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
2 changes: 2 additions & 0 deletions homeassistant/helpers/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,8 @@ def _stringify_state(self) -> str:
# If the entity's state is a float, limit precision according to machine
# epsilon to make the string representation readable
return f"{state:.{FLOAT_PRECISION}}"
if isinstance(state, datetime):
return state.isoformat()
return str(state)

@callback
Expand Down
3 changes: 2 additions & 1 deletion homeassistant/helpers/typing.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Typing Helpers for Home Assistant."""
from datetime import datetime
from enum import Enum
from typing import Any, Dict, Mapping, Optional, Tuple, Union

Expand All @@ -10,7 +11,7 @@
DiscoveryInfoType = Dict[str, Any]
EventType = homeassistant.core.Event
ServiceDataType = Dict[str, Any]
StateType = Union[None, str, int, float]
StateType = Union[None, str, int, float, datetime]
TemplateVarsType = Optional[Mapping[str, Any]]

# Custom type for recorder Queries
Expand Down
16 changes: 15 additions & 1 deletion tests/helpers/test_entity.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Test the entity helper."""
# pylint: disable=protected-access
import asyncio
from datetime import timedelta
from datetime import datetime, timedelta, timezone
import threading
from unittest.mock import MagicMock, PropertyMock, patch

Expand Down Expand Up @@ -788,3 +788,17 @@ async def test_float_conversion(hass):
state = hass.states.get("hello.world")
assert state is not None
assert state.state == "3.6"


async def test_datetime_conversion(hass):
"""Test conversion of datetime state to ISO 8601 datetime strings."""
object_state = datetime(2017, 12, 19, 18, 29, 42, tzinfo=timezone.utc)
with patch.object(entity.Entity, "state", PropertyMock(return_value=object_state)):
ent = entity.Entity()
ent.hass = hass
ent.entity_id = "hello.world"
ent.async_write_ha_state()

state = hass.states.get("hello.world")
assert state is not None
assert state.state == "2017-12-19T18:29:42+00:00"

0 comments on commit d4470af

Please sign in to comment.