diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index f65100a8775..d991a0b58f2 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -1420,6 +1420,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.filters["atan"] = arc_tangent self.filters["atan2"] = arc_tangent2 self.filters["sqrt"] = square_root + self.filters["as_datetime"] = dt_util.parse_datetime self.filters["as_timestamp"] = forgiving_as_timestamp self.filters["as_local"] = dt_util.as_local self.filters["timestamp_custom"] = timestamp_custom @@ -1454,6 +1455,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.globals["atan"] = arc_tangent self.globals["atan2"] = arc_tangent2 self.globals["float"] = forgiving_float + self.globals["as_datetime"] = dt_util.parse_datetime self.globals["as_local"] = dt_util.as_local self.globals["as_timestamp"] = forgiving_as_timestamp self.globals["relative_time"] = relative_time diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 48ef6f25b67..1818d8c4876 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -526,6 +526,33 @@ def test_timestamp_local(hass): ) +@pytest.mark.parametrize( + "input", + ( + "2021-06-03 13:00:00.000000+00:00", + "1986-07-09T12:00:00Z", + "2016-10-19 15:22:05.588122+0100", + "2016-10-19", + "2021-01-01 00:00:01", + "invalid", + ), +) +def test_as_datetime(hass, input): + """Test converting a timestamp string to a date object.""" + expected = dt_util.parse_datetime(input) + if expected is not None: + expected = str(expected) + + assert ( + template.Template(f"{{{{ as_datetime('{input}') }}}}", hass).async_render() + == expected + ) + assert ( + template.Template(f"{{{{ '{input}' | as_datetime }}}}", hass).async_render() + == expected + ) + + def test_as_local(hass): """Test converting time to local."""