1
0
mirror of https://github.com/home-assistant/core.git synced 2025-12-24 21:06:19 +00:00

Add timestamp filters (#2596)

This commit is contained in:
Fabian Affolter
2016-07-23 04:47:43 +02:00
committed by Paulus Schoutsen
parent 3122c0279f
commit 57c2dea02d
2 changed files with 50 additions and 0 deletions

View File

@@ -15,6 +15,7 @@ from homeassistant.util import convert, dt as dt_util, location as loc_util
_LOGGER = logging.getLogger(__name__)
_SENTINEL = object()
DATE_STR_FORMAT = "%Y-%m-%d %H:%M:%S"
def render_with_possible_json_value(hass, template, value,
@@ -248,6 +249,25 @@ def multiply(value, amount):
return value
def timestamp_local(value):
"""Filter to convert given timestamp to local date/time."""
try:
return dt_util.as_local(
dt_util.utc_from_timestamp(value)).strftime(DATE_STR_FORMAT)
except (ValueError, TypeError):
# If timestamp can't be converted
return value
def timestamp_utc(value):
"""Filter to convert gibrn timestamp to UTC date/time."""
try:
return dt_util.utc_from_timestamp(value).strftime(DATE_STR_FORMAT)
except (ValueError, TypeError):
# If timestamp can't be converted
return value
def forgiving_float(value):
"""Try to convert value to a float."""
try:
@@ -266,3 +286,5 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment):
ENV = TemplateEnvironment()
ENV.filters['round'] = forgiving_round
ENV.filters['multiply'] = multiply
ENV.filters['timestamp_local'] = timestamp_local
ENV.filters['timestamp_utc'] = timestamp_utc