diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 056a4e60183..e083534f828 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -252,6 +252,20 @@ def multiply(value, amount): return value +def timestamp_custom(value, date_format=DATE_STR_FORMAT, local=True): + """Filter to convert given timestamp to format.""" + try: + date = dt_util.utc_from_timestamp(value) + + if local: + date = dt_util.as_local(date) + + return date.strftime(date_format) + except (ValueError, TypeError): + # If timestamp can't be converted + return value + + def timestamp_local(value): """Filter to convert given timestamp to local date/time.""" try: @@ -263,7 +277,7 @@ def timestamp_local(value): def timestamp_utc(value): - """Filter to convert gibrn timestamp to UTC date/time.""" + """Filter to convert given timestamp to UTC date/time.""" try: return dt_util.utc_from_timestamp(value).strftime(DATE_STR_FORMAT) except (ValueError, TypeError): @@ -289,5 +303,6 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): ENV = TemplateEnvironment() ENV.filters['round'] = forgiving_round ENV.filters['multiply'] = multiply +ENV.filters['timestamp_custom'] = timestamp_custom 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 266138d1fd5..64bac46264d 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -127,6 +127,30 @@ class TestUtilTemplate(unittest.TestCase): template.render(self.hass, '{{ %s | multiply(10) | round }}' % inp)) + def test_timestamp_custom(self): + """Test the timestamps to custom filter.""" + tests = [ + (None, None, None, 'None'), + (1469119144, None, True, '2016-07-21 16:39:04'), + (1469119144, '%Y', True, '2016'), + (1469119144, 'invalid', True, 'invalid'), + (dt_util.as_timestamp(dt_util.utcnow()), None, False, + dt_util.now().strftime('%Y-%m-%d %H:%M:%S')) + ] + + for inp, fmt, local, out in tests: + if fmt: + fil = 'timestamp_custom(\'{}\')'.format(fmt) + elif fmt and local: + fil = 'timestamp_custom(\'{0}\', {1})'.format(fmt, local) + else: + fil = 'timestamp_custom' + + self.assertEqual( + out, + template.render(self.hass, '{{ %s | %s }}' % (inp, fil)) + ) + def test_timestamp_local(self): """Test the timestamps to local filter.""" tests = {