Add timestamp filters (#2596)

pull/2605/head
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

View File

@ -117,6 +117,34 @@ class TestUtilTemplate(unittest.TestCase):
template.render(self.hass,
'{{ %s | multiply(10) | round }}' % inp))
def test_timestamp_local(self):
"""Test the timestamps to local filter."""
tests = {
None: 'None',
1469119144: '2016-07-21 16:39:04',
}
for inp, out in tests.items():
self.assertEqual(
out,
template.render(self.hass,
'{{ %s | timestamp_local }}' % inp))
def test_timestamp_utc(self):
"""Test the timestamps to local filter."""
tests = {
None: 'None',
1469119144: '2016-07-21 16:39:04',
dt_util.as_timestamp(dt_util.utcnow()):
dt_util.now().strftime('%Y-%m-%d %H:%M:%S')
}
for inp, out in tests.items():
self.assertEqual(
out,
template.render(self.hass,
'{{ %s | timestamp_utc }}' % inp))
def test_passing_vars_as_keywords(self):
"""."""
self.assertEqual(