Add easy converting string timestamps/dates to datetime objects in templates (#51576)

This commit is contained in:
Franck Nijhof 2021-06-07 15:02:15 +02:00 committed by GitHub
parent 4227a01e62
commit 4c51299dcc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 0 deletions

View File

@ -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

View File

@ -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."""