mirror of
https://github.com/home-assistant/core.git
synced 2025-04-23 16:57:53 +00:00
Add UNIX timestamp detection to as_datetime
template filter (#60126)
This commit is contained in:
parent
fa0d3a6c48
commit
d41d223033
@ -1494,6 +1494,16 @@ def forgiving_as_timestamp(value, default=_SENTINEL):
|
||||
return default
|
||||
|
||||
|
||||
def as_datetime(value):
|
||||
"""Filter and to convert a time string or UNIX timestamp to datetime object."""
|
||||
try:
|
||||
# Check for a valid UNIX timestamp string, int or float
|
||||
timestamp = float(value)
|
||||
return dt_util.utc_from_timestamp(timestamp)
|
||||
except ValueError:
|
||||
return dt_util.parse_datetime(value)
|
||||
|
||||
|
||||
def strptime(string, fmt, default=_SENTINEL):
|
||||
"""Parse a time string to datetime."""
|
||||
try:
|
||||
@ -1789,7 +1799,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_datetime"] = as_datetime
|
||||
self.filters["as_timestamp"] = forgiving_as_timestamp
|
||||
self.filters["today_at"] = today_at
|
||||
self.filters["as_local"] = dt_util.as_local
|
||||
@ -1830,7 +1840,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_datetime"] = as_datetime
|
||||
self.globals["as_local"] = dt_util.as_local
|
||||
self.globals["as_timestamp"] = forgiving_as_timestamp
|
||||
self.globals["today_at"] = today_at
|
||||
|
@ -732,6 +732,36 @@ def test_as_datetime(hass, input):
|
||||
)
|
||||
|
||||
|
||||
def test_as_datetime_from_timestamp(hass):
|
||||
"""Test converting a UNIX timestamp to a date object."""
|
||||
tests = [
|
||||
(1469119144, "2016-07-21 16:39:04+00:00"),
|
||||
(1469119144.0, "2016-07-21 16:39:04+00:00"),
|
||||
(-1, "1969-12-31 23:59:59+00:00"),
|
||||
]
|
||||
for input, output in tests:
|
||||
# expected = dt_util.parse_datetime(input)
|
||||
if output is not None:
|
||||
output = str(output)
|
||||
|
||||
assert (
|
||||
template.Template(f"{{{{ as_datetime({input}) }}}}", hass).async_render()
|
||||
== output
|
||||
)
|
||||
assert (
|
||||
template.Template(f"{{{{ {input} | as_datetime }}}}", hass).async_render()
|
||||
== output
|
||||
)
|
||||
assert (
|
||||
template.Template(f"{{{{ as_datetime('{input}') }}}}", hass).async_render()
|
||||
== output
|
||||
)
|
||||
assert (
|
||||
template.Template(f"{{{{ '{input}' | as_datetime }}}}", hass).async_render()
|
||||
== output
|
||||
)
|
||||
|
||||
|
||||
def test_as_local(hass):
|
||||
"""Test converting time to local."""
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user