diff --git a/homeassistant/components/tod/binary_sensor.py b/homeassistant/components/tod/binary_sensor.py index 5b4a6e12459..6f14d5735fb 100644 --- a/homeassistant/components/tod/binary_sensor.py +++ b/homeassistant/components/tod/binary_sensor.py @@ -161,6 +161,21 @@ class TodSensor(BinarySensorEntity): self._time_before = before_event_date + # We are calculating the _time_after value assuming that it will happen today + # But that is not always true, e.g. after 23:00, before 12:00 and now is 10:00 + # If _time_before and _time_after are ahead of nowutc: + # _time_before is set to 12:00 next day + # _time_after is set to 23:00 today + # nowutc is set to 10:00 today + if ( + not is_sun_event(self._after) + and self._time_after > nowutc + and self._time_before > nowutc + timedelta(days=1) + ): + # remove one day from _time_before and _time_after + self._time_after -= timedelta(days=1) + self._time_before -= timedelta(days=1) + # Add offset to utc boundaries according to the configuration self._time_after += self._after_offset self._time_before += self._before_offset diff --git a/tests/components/tod/test_binary_sensor.py b/tests/components/tod/test_binary_sensor.py index ef8088d6aab..06f29436d6e 100644 --- a/tests/components/tod/test_binary_sensor.py +++ b/tests/components/tod/test_binary_sensor.py @@ -163,6 +163,25 @@ async def test_midnight_turnover_before_midnight_outside_period(hass): assert state.state == STATE_OFF +async def test_after_happens_tomorrow(hass): + """Test when both before and after are in the future, and after is later than before.""" + test_time = datetime(2019, 1, 10, 10, 00, 0, tzinfo=dt_util.UTC) + config = { + "binary_sensor": [ + {"platform": "tod", "name": "Night", "after": "23:00", "before": "12:00"} + ] + } + with patch( + "homeassistant.components.tod.binary_sensor.dt_util.utcnow", + return_value=test_time, + ): + await async_setup_component(hass, "binary_sensor", config) + await hass.async_block_till_done() + + state = hass.states.get("binary_sensor.night") + assert state.state == STATE_ON + + async def test_midnight_turnover_after_midnight_outside_period(hass): """Test midnight turnover setting before midnight inside period .""" test_time = datetime(2019, 1, 10, 20, 0, 0, tzinfo=dt_util.UTC)