Automation and template with error messages in log about invalid date/time values

Hello!

I use OpenWeatherMap (once_hourly) and the following in templates.yaml (included in configuration.yaml):

  sensor:

    - name: Frost Alert
      unique_id: frost_alert
      state: >
        {% set start = (now().date()+ timedelta(days=1)) | string + "T04:00:00+00:00"%}
        {% set end = (now().date()+ timedelta(days=1)) | string + "T08:00:00+00:00"%}
        {% set temp_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | map(attribute="temperature") | list | min)%}
        {% set result_frost_alert = temp_frost_alert < 4 %}
        {{result_frost_alert}}

    - name: Frost Temperature
      unique_id: frost_temperature
      state: >
        {% set start = (now().date()+ timedelta(days=1)) | string + "T04:00:00+00:00"%}
        {% set end = (now().date()+ timedelta(days=1)) | string + "T08:00:00+00:00"%}
        {% set temp_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | map(attribute="temperature") | list | min)%}
        {{temp_frost_alert}}
      
    - name: Frost Time
      unique_id: frost_time
      state: >
        {% set start = (now().date()+ timedelta(days=1)) | string + "T04:00:00+00:00"%}
        {% set end = (now().date()+ timedelta(days=1)) | string + "T08:00:00+00:00"%}
        {% set temp_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | map(attribute="temperature") | list | min)%}
        {% set result_frost_alert = temp_frost_alert < 4 %}
                {% set time_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | selectattr("temperature", "eq", temp_frost_alert)| map(attribute="datetime") | list | join )%}
        {{as_timestamp(time_frost_alert) | timestamp_custom("%H:%M")}}

(source: Home Assistant Frost Alert - daniel-strohbach.de)

In principle it works, i.e. I get automated notifications about potential frost, but I don’t know how to solve these related errors in the log:

Logger: homeassistant.helpers.event
Source: helpers/template.py:570
First occurred: 08:20:28 (1 occurrences)
Last logged: 08:20:28

Error while processing template: Template<template=({% set start = (now().date()+ timedelta(days=1)) | string + "T04:00:00+00:00"%} {% set end = (now().date()+ timedelta(days=1)) | string + "T08:00:00+00:00"%} {% set temp_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | map(attribute="temperature") | list | min)%} {% set result_frost_alert = temp_frost_alert < 4 %} {% set time_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | selectattr("temperature", "eq", temp_frost_alert)| map(attribute="datetime") | list | join )%} {{as_timestamp(time_frost_alert) | timestamp_custom("%H:%M")}}) renders=2>
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1821, in forgiving_as_timestamp
    return dt_util.as_timestamp(value)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/util/dt.py", line 135, in as_timestamp
    raise ValueError("not a valid date/time.")
ValueError: not a valid date/time.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 568, in async_render
    render_result = _render_with_context(self.template, compiled, **kwargs)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2196, in _render_with_context
    return template.render(**kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/jinja2/environment.py", line 1301, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.11/site-packages/jinja2/environment.py", line 936, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 3, in top-level template code
  File "/usr/local/lib/python3.11/site-packages/jinja2/sandbox.py", line 393, in call
    return __context.call(__obj, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1824, in forgiving_as_timestamp
    raise_no_default("as_timestamp", value)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1626, in raise_no_default
    raise ValueError(
ValueError: Template error: as_timestamp got invalid input '2023-10-18T04:00:00+00:002023-10-18T05:00:00+00:00' when rendering template '{% set start = (now().date()+ timedelta(days=1)) | string + "T04:00:00+00:00"%} {% set end = (now().date()+ timedelta(days=1)) | string + "T08:00:00+00:00"%} {% set temp_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | map(attribute="temperature") | list | min)%} {% set result_frost_alert = temp_frost_alert < 4 %}
        {% set time_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | selectattr("temperature", "eq", temp_frost_alert)| map(attribute="datetime") | list | join )%}
{{as_timestamp(time_frost_alert) | timestamp_custom("%H:%M")}}' but no default was specified

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 694, in async_render_to_info
    render_info._result = self.async_render(
                          ^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 570, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: ValueError: Template error: as_timestamp got invalid input '2023-10-18T04:00:00+00:002023-10-18T05:00:00+00:00' when rendering template '{% set start = (now().date()+ timedelta(days=1)) | string + "T04:00:00+00:00"%} {% set end = (now().date()+ timedelta(days=1)) | string + "T08:00:00+00:00"%} {% set temp_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | map(attribute="temperature") | list | min)%} {% set result_frost_alert = temp_frost_alert < 4 %}
        {% set time_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | selectattr("temperature", "eq", temp_frost_alert)| map(attribute="datetime") | list | join )%}
{{as_timestamp(time_frost_alert) | timestamp_custom("%H:%M")}}' but no default was specified

And:

Logger: homeassistant.components.template.template_entity
Source: components/template/template_entity.py:194
Integration: Template (documentation, issues)
First occurred: 08:20:28 (1 occurrences)
Last logged: 08:20:28

TemplateError('ValueError: Template error: as_timestamp got invalid input '2023-10-18T04:00:00+00:002023-10-18T05:00:00+00:00' when rendering template '{% set start = (now().date()+ timedelta(days=1)) | string + "T04:00:00+00:00"%} {% set end = (now().date()+ timedelta(days=1)) | string + "T08:00:00+00:00"%} {% set temp_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | map(attribute="temperature") | list | min)%} {% set result_frost_alert = temp_frost_alert < 4 %} {% set time_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | selectattr("temperature", "eq", temp_frost_alert)| map(attribute="datetime") | list | join )%} {{as_timestamp(time_frost_alert) | timestamp_custom("%H:%M")}}' but no default was specified') while processing template 'Template<template=({% set start = (now().date()+ timedelta(days=1)) | string + "T04:00:00+00:00"%} {% set end = (now().date()+ timedelta(days=1)) | string + "T08:00:00+00:00"%} {% set temp_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | map(attribute="temperature") | list | min)%} {% set result_frost_alert = temp_frost_alert < 4 %} {% set time_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | selectattr("temperature", "eq", temp_frost_alert)| map(attribute="datetime") | list | join )%} {{as_timestamp(time_frost_alert) | timestamp_custom("%H:%M")}}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.frost_time'

Any help is very much appreciated - thank you! :blush:

The error is caused by this line:

{% set time_frost_alert = (state_attr('weather.openweathermap_hourly', 'forecast') | selectattr("datetime", ">=", start) | selectattr("datetime", "<=", end) | selectattr("temperature", "eq", temp_frost_alert)| map(attribute="datetime") | list | join )%}

It finds two datetimes that are between start and end. Then it converts the two datetimes into strings and combines them to produce something like this:

2023-10-18T04:00:00+00:002023-10-18T05:00:00+00:00

That’s not a valid datetime so the as_timestamp filter cannot process it and produces the error message you received.

I suggest you replace join with first. Then you have to improve the last line of the template:

{{as_timestamp(time_frost_alert) | timestamp_custom("%H:%M")}}

Why? Because it assumes time_frost_alert always has a value. If it has no value (because there’s no frost in the forecast) the as_timestamp filter will fail.

You may wish to do something like this:

{{ as_timestamp(time_frost_alert) | timestamp_custom("%H:%M") if time_frost_alert else '' }}
1 Like

Dear Taras,

Thank you so much that you took your time for this very kind and precise explanation and solution. First, I am happy that it works now, and second, I have also learnt something new from your answer. Wishing you all the best! :grinning::+1:

Cheers
7wells

1 Like