diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 105260475e4..dac568439e4 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -1,4 +1,5 @@ """Template helper methods for rendering strings with HA data.""" +from datetime import datetime import json import logging import re @@ -386,6 +387,14 @@ def timestamp_utc(value): return value +def strptime(string, fmt): + """Parse a time string to datetime.""" + try: + return datetime.strptime(string, fmt) + except (ValueError, AttributeError): + return string + + def fail_when_undefined(value): """Filter to force a failure when the value is undefined.""" if isinstance(value, jinja2.Undefined): @@ -420,3 +429,4 @@ ENV.globals['now'] = dt_util.now ENV.globals['utcnow'] = dt_util.utcnow ENV.globals['as_timestamp'] = dt_util.as_timestamp ENV.globals['relative_time'] = dt_util.get_age +ENV.globals['strptime'] = strptime diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 31f90233701..463f073eeb1 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -1,4 +1,5 @@ """Test Home Assistant template helper methods.""" +from datetime import datetime import unittest from unittest.mock import patch @@ -122,6 +123,32 @@ class TestHelpersTemplate(unittest.TestCase): template.Template('{{ %s | multiply(10) | round }}' % inp, self.hass).render()) + def test_strptime(self): + """Test the parse timestamp method.""" + tests = [ + ('2016-10-19 15:22:05.588122 UTC', + '%Y-%m-%d %H:%M:%S.%f %Z', None), + ('2016-10-19 15:22:05.588122+0100', + '%Y-%m-%d %H:%M:%S.%f%z', None), + ('2016-10-19 15:22:05.588122', + '%Y-%m-%d %H:%M:%S.%f', None), + ('2016-10-19', '%Y-%m-%d', None), + ('2016', '%Y', None), + ('15:22:05', '%H:%M:%S', None), + ('1469119144', '%Y', '1469119144'), + ('invalid', '%Y', 'invalid') + ] + + for inp, fmt, expected in tests: + if expected is None: + expected = datetime.strptime(inp, fmt) + + temp = '{{ strptime(\'%s\', \'%s\') }}' % (inp, fmt) + + self.assertEqual( + str(expected), + template.Template(temp, self.hass).render()) + def test_timestamp_custom(self): """Test the timestamps to custom filter.""" tests = [