Skip to content

Commit

Permalink
Fix setting timestamp on input_datetime (#44274)
Browse files Browse the repository at this point in the history
  • Loading branch information
balloob authored Dec 16, 2020
1 parent dfde403 commit 4f9d579
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
8 changes: 3 additions & 5 deletions homeassistant/components/input_datetime/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,9 +365,7 @@ def unique_id(self) -> typing.Optional[str]:
def async_set_datetime(self, date=None, time=None, datetime=None, timestamp=None):
"""Set a new date / time."""
if timestamp:
datetime = dt_util.as_local(dt_util.utc_from_timestamp(timestamp)).replace(
tzinfo=None
)
datetime = dt_util.as_local(dt_util.utc_from_timestamp(timestamp))

if datetime:
date = datetime.date()
Expand All @@ -388,8 +386,8 @@ def async_set_datetime(self, date=None, time=None, datetime=None, timestamp=None
if not time:
time = self._current_datetime.time()

self._current_datetime = py_datetime.datetime.combine(date, time).replace(
tzinfo=dt_util.DEFAULT_TIME_ZONE
self._current_datetime = dt_util.DEFAULT_TIME_ZONE.localize(
py_datetime.datetime.combine(date, time)
)
self.async_write_ha_state()

Expand Down
28 changes: 28 additions & 0 deletions tests/components/input_datetime/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,12 +697,40 @@ async def test_timestamp(hass):
).strftime(FMT_DATETIME)
== "2020-12-13 10:00:00"
)
# Use datetime.datetime.fromtimestamp
assert (
dt_util.as_local(
datetime.datetime.fromtimestamp(
state_without_tz.attributes[ATTR_TIMESTAMP]
)
).strftime(FMT_DATETIME)
== "2020-12-13 10:00:00"
)

# Test initial time sets timestamp correctly.
state_time = hass.states.get("input_datetime.test_time_initial")
assert state_time is not None
assert state_time.state == "10:00:00"
assert state_time.attributes[ATTR_TIMESTAMP] == 10 * 60 * 60

# Test that setting the timestamp of an entity works.
await hass.services.async_call(
DOMAIN,
"set_datetime",
{
ATTR_ENTITY_ID: "input_datetime.test_datetime_initial_with_tz",
ATTR_TIMESTAMP: state_without_tz.attributes[ATTR_TIMESTAMP],
},
blocking=True,
)
state_with_tz_updated = hass.states.get(
"input_datetime.test_datetime_initial_with_tz"
)
assert state_with_tz_updated.state == "2020-12-13 10:00:00"
assert (
state_with_tz_updated.attributes[ATTR_TIMESTAMP]
== state_without_tz.attributes[ATTR_TIMESTAMP]
)

finally:
dt_util.set_default_time_zone(ORIG_TIMEZONE)

0 comments on commit 4f9d579

Please sign in to comment.