Add strptime template function (#3950)
This commit is contained in:
parent
cd1b0ac67d
commit
01a6c1c1c8
2 changed files with 37 additions and 0 deletions
|
@ -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
|
||||
|
|
|
@ -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 = [
|
||||
|
|
Loading…
Add table
Reference in a new issue