diff --git a/homeassistant/components/time_date/sensor.py b/homeassistant/components/time_date/sensor.py index b9012385296891..9f2cdf304cda6f 100644 --- a/homeassistant/components/time_date/sensor.py +++ b/homeassistant/components/time_date/sensor.py @@ -112,16 +112,6 @@ def _update_internal_state(self, time_date): date = dt_util.as_local(time_date).date().isoformat() date_utc = time_date.date().isoformat() - # Calculate Swatch Internet Time. - time_bmt = time_date + timedelta(hours=1) - delta = timedelta( - hours=time_bmt.hour, - minutes=time_bmt.minute, - seconds=time_bmt.second, - microseconds=time_bmt.microsecond, - ) - beat = int((delta.seconds + delta.microseconds / 1000000.0) / 86.4) - if self.type == "time": self._state = time elif self.type == "date": @@ -135,6 +125,19 @@ def _update_internal_state(self, time_date): elif self.type == "time_utc": self._state = time_utc elif self.type == "beat": + # Calculate Swatch Internet Time. + time_bmt = time_date + timedelta(hours=1) + delta = timedelta( + hours=time_bmt.hour, + minutes=time_bmt.minute, + seconds=time_bmt.second, + microseconds=time_bmt.microsecond, + ) + + # Use integers to better handle rounding. For example, + # int(63763.2/86.4) = 737 but 637632//864 = 738. + beat = int(delta.total_seconds() * 10) // 864 + self._state = f"@{beat:03d}" elif self.type == "date_time_iso": self._state = dt_util.parse_datetime(f"{date} {time}").isoformat() diff --git a/tests/components/time_date/test_sensor.py b/tests/components/time_date/test_sensor.py index a20afb61fe3d3f..b4161dab948faa 100644 --- a/tests/components/time_date/test_sensor.py +++ b/tests/components/time_date/test_sensor.py @@ -66,6 +66,8 @@ async def test_states(hass): device = time_date.TimeDateSensor(hass, "beat") device._update_internal_state(now) assert device.state == "@079" + device._update_internal_state(dt_util.utc_from_timestamp(1602952963.2)) + assert device.state == "@738" device = time_date.TimeDateSensor(hass, "date_time_iso") device._update_internal_state(now)