diff --git a/homeassistant/components/command_line/sensor.py b/homeassistant/components/command_line/sensor.py index 1b865827e69..dd5ad2d5190 100644 --- a/homeassistant/components/command_line/sensor.py +++ b/homeassistant/components/command_line/sensor.py @@ -15,9 +15,11 @@ from homeassistant.components.sensor import ( DOMAIN as SENSOR_DOMAIN, PLATFORM_SCHEMA, STATE_CLASSES_SCHEMA, + SensorDeviceClass, SensorEntity, SensorStateClass, ) +from homeassistant.components.sensor.helpers import async_parse_date_datetime from homeassistant.const import ( CONF_COMMAND, CONF_DEVICE_CLASS, @@ -206,14 +208,24 @@ class CommandSensor(ManualTriggerEntity, SensorEntity): return if self._value_template is not None: - self._attr_native_value = ( - self._value_template.async_render_with_possible_json_value( - value, - None, - ) + value = self._value_template.async_render_with_possible_json_value( + value, + None, ) - else: + + if self.device_class not in { + SensorDeviceClass.DATE, + SensorDeviceClass.TIMESTAMP, + }: self._attr_native_value = value + self._process_manual_data(value) + return + + self._attr_native_value = None + if value is not None: + self._attr_native_value = async_parse_date_datetime( + value, self.entity_id, self.device_class + ) self._process_manual_data(value) self.async_write_ha_state() diff --git a/tests/components/command_line/test_sensor.py b/tests/components/command_line/test_sensor.py index a0f8f2cdf84..bc24ff5419f 100644 --- a/tests/components/command_line/test_sensor.py +++ b/tests/components/command_line/test_sensor.py @@ -646,3 +646,54 @@ async def test_updating_manually( ) await hass.async_block_till_done() assert called + + +@pytest.mark.parametrize( + "get_config", + [ + { + "command_line": [ + { + "sensor": { + "name": "Test", + "command": "echo 2022-12-22T13:15:30Z", + "device_class": "timestamp", + } + } + ] + } + ], +) +async def test_scrape_sensor_device_timestamp( + hass: HomeAssistant, load_yaml_integration: None +) -> None: + """Test Command Line sensor with a device of type TIMESTAMP.""" + entity_state = hass.states.get("sensor.test") + assert entity_state + assert entity_state.state == "2022-12-22T13:15:30+00:00" + + +@pytest.mark.parametrize( + "get_config", + [ + { + "command_line": [ + { + "sensor": { + "name": "Test", + "command": "echo January 17, 2022", + "device_class": "date", + "value_template": "{{ strptime(value, '%B %d, %Y').strftime('%Y-%m-%d') }}", + } + } + ] + } + ], +) +async def test_scrape_sensor_device_date( + hass: HomeAssistant, load_yaml_integration: None +) -> None: + """Test Command Line sensor with a device of type DATE.""" + entity_state = hass.states.get("sensor.test") + assert entity_state + assert entity_state.state == "2022-01-17"