mirror of
https://github.com/home-assistant/core.git
synced 2025-04-23 00:37:53 +00:00
Return None instead of raising ValueException from as_timestamp template function. (#6155)
This commit is contained in:
parent
8a67fcfee3
commit
4da2156ebf
@ -387,6 +387,14 @@ def timestamp_utc(value):
|
||||
return value
|
||||
|
||||
|
||||
def forgiving_as_timestamp(value):
|
||||
"""Try to convert value to timestamp."""
|
||||
try:
|
||||
return dt_util.as_timestamp(value)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def strptime(string, fmt):
|
||||
"""Parse a time string to datetime."""
|
||||
try:
|
||||
@ -430,6 +438,6 @@ ENV.filters['min'] = min
|
||||
ENV.globals['float'] = forgiving_float
|
||||
ENV.globals['now'] = dt_util.now
|
||||
ENV.globals['utcnow'] = dt_util.utcnow
|
||||
ENV.globals['as_timestamp'] = dt_util.as_timestamp
|
||||
ENV.globals['as_timestamp'] = forgiving_as_timestamp
|
||||
ENV.globals['relative_time'] = dt_util.get_age
|
||||
ENV.globals['strptime'] = strptime
|
||||
|
@ -215,6 +215,21 @@ class TestHelpersTemplate(unittest.TestCase):
|
||||
template.Template('{{ %s | timestamp_utc }}' % inp,
|
||||
self.hass).render())
|
||||
|
||||
def test_as_timestamp(self):
|
||||
"""Test the as_timestamp function."""
|
||||
self.assertEqual("None",
|
||||
template.Template('{{ as_timestamp("invalid") }}',
|
||||
self.hass).render())
|
||||
self.hass.mock = None
|
||||
self.assertEqual("None",
|
||||
template.Template('{{ as_timestamp(states.mock) }}',
|
||||
self.hass).render())
|
||||
|
||||
tpl = '{{ as_timestamp(strptime("2024-02-03T09:10:24+0000", ' \
|
||||
'"%Y-%m-%dT%H:%M:%S%z")) }}'
|
||||
self.assertEqual("1706951424.0",
|
||||
template.Template(tpl, self.hass).render())
|
||||
|
||||
def test_passing_vars_as_keywords(self):
|
||||
"""Test passing variables as keywords."""
|
||||
self.assertEqual(
|
||||
|
Loading…
x
Reference in New Issue
Block a user