Add additional template for custom date formats (#3262)

I can live with a few visual line breaks 🐬
This commit is contained in:
Lewis Juggins 2016-09-09 01:49:02 +01:00 committed by Teagan Glenn
parent ee6c83f569
commit 44f5a66b66
2 changed files with 40 additions and 1 deletions

View File

@ -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

View File

@ -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 = {