From 57c2dea02d989317c9de20f540efc9810c68ed57 Mon Sep 17 00:00:00 2001 From: Fabian Affolter Date: Sat, 23 Jul 2016 04:47:43 +0200 Subject: [PATCH] Add timestamp filters (#2596) --- homeassistant/helpers/template.py | 22 ++++++++++++++++++++++ tests/helpers/test_template.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 41de1782a1f..8ccfd1e0bf5 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -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 diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 9aa91c3cd1a..1529c879aab 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -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(