Template error on startup complaining as_timestamp() gets unknown as parameter

I get an error for a template sensor: “Error while processing template”, but at at startup only. How to avoid the error at startup?

The code is executed fine in the Dev tools / template editor.

The detailed error mentions as_timestamp() - got invalid input ‘unknown’ - as the origin.

The sensor definition:

- sensor:
    - name: "Unavailable Zigbee devices info"
      unique_id: "ff0fb012-8a84-452d-88d0-9c9a4a6a7e03"
      icon: mdi:counter
      availability: "true"
      unit_of_measurement: "cm"
      state: 0
      attributes:
        unavailable_device_names: >-
          {% set result = namespace(sensors=[]) %}
          {% for state in states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', '==', 'timestamp') %}
              {% if 'last_seen' in state.entity_id and (states(state.entity_id) == 'unavailable' or ((as_timestamp(now()) - as_timestamp(states(state.entity_id))) > ((24 | int) * 60 * 60))) %}
                  {% set result.sensors = result.sensors + ['- ' + state.name | regex_replace(find=' Last seen', replace='')] %}
              {% endif %}
          {% endfor %}
          {{ result.sensors | join('\n') | truncate(254, True) }}
        device_list_length: >-
          {%- set hash_value=state_attr('sensor.unavailable_zigbee_devices_info', 'unavailable_device_names') | join('\n') | length %}
          {{ hash_value }}

The log file entry:

Logger: homeassistant.helpers.event
Source: helpers/template.py:646
First occurred: 19:46:18 (2 occurrences)
Last logged: 19:46:18

Error while processing template: Template<template=({% set result = namespace(sensors=[]) %} {% for state in states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', '==', 'timestamp') %} {% if 'last_seen' in state.entity_id and (states(state.entity_id) == 'unavailable' or ((as_timestamp(now()) - as_timestamp(states(state.entity_id))) > ((24 | int) * 60 * 60))) %} {% set result.sensors = result.sensors + ['- ' + state.name | regex_replace(find=' Last seen', replace='')] %} {% endif %} {% endfor %} {{ result.sensors | join('\n') | truncate(254, True) }}) renders=2>
Error while processing template: Template<template=({%- set hash_value=state_attr('sensor.unavailable_zigbee_devices_info', 'unavailable_device_names') | join('\n') | length %} {{ hash_value }}) renders=2>
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2206, in forgiving_as_timestamp
    return dt_util.as_timestamp(value)
           ~~~~~~~~~~~~~~~~~~~~^^^^^^^
  File "/usr/src/homeassistant/homeassistant/util/dt.py", line 155, 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 644, in async_render
    render_result = _render_with_context(self.template, compiled, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2969, in _render_with_context
    return template.render(**kwargs)
           ~~~~~~~~~~~~~~~^^^^^^^^^^
  File "/usr/local/lib/python3.13/site-packages/jinja2/environment.py", line 1295, in render
    self.environment.handle_exception()
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "/usr/local/lib/python3.13/site-packages/jinja2/environment.py", line 942, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 2, in top-level template code
  File "/usr/local/lib/python3.13/site-packages/jinja2/sandbox.py", line 401, in call
    return __context.call(__obj, *args, **kwargs)
           ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2209, in forgiving_as_timestamp
    raise_no_default("as_timestamp", value)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1972, in raise_no_default
    raise ValueError(
    ...<2 lines>...
    )
ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{% set result = namespace(sensors=[]) %} {% for state in states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', '==', 'timestamp') %}
    {% if 'last_seen' in state.entity_id and (states(state.entity_id) == 'unavailable' or ((as_timestamp(now()) - as_timestamp(states(state.entity_id))) > ((24 | int) * 60 * 60))) %}
        {% set result.sensors = result.sensors + ['- ' + state.name | regex_replace(find=' Last seen', replace='')] %}
    {% endif %}
{% endfor %} {{ result.sensors | join('\n') | truncate(254, True) }}' 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 761, in async_render_to_info
    render_info._result = self.async_render(  # noqa: SLF001
                          ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
        variables, strict=strict, log_fn=log_fn, **kwargs
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 646, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{% set result = namespace(sensors=[]) %} {% for state in states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', '==', 'timestamp') %}
    {% if 'last_seen' in state.entity_id and (states(state.entity_id) == 'unavailable' or ((as_timestamp(now()) - as_timestamp(states(state.entity_id))) > ((24 | int) * 60 * 60))) %}
        {% set result.sensors = result.sensors + ['- ' + state.name | regex_replace(find=' Last seen', replace='')] %}
    {% endif %}
{% endfor %} {{ result.sensors | join('\n') | truncate(254, True) }}' but no default was specified

I replaced your template with ... so you can fully see the entire error message.

1 Like

Why are you making your attribute a list-shaped strings instead of just using an actual list…?

Do you really want a character/letter count for the value of device_list_length?

Thanks for pointing me to the obvious! Somehow I did not see the tree as the forrest was in the way. :sweat_smile:
Moral of the story: Do not just cut and paste something one finds on the internet assuming it works like charm. :sweat_smile:

1 Like

May I ask what was the source of this example? I’m curious to know why it has such an odd design.

Oddities:

  • Its unit of measurement is cm but its reported value is hard-coded as zero.
  • The value it does compute isn’t related to distance or length.
  • It explicitly hard-codes availability to true (as a string value).

Only the Jinja part of the sensor was Cut&Paste. I found the snippet on Managing Offline Devices in Zigbee2MQTT — Home Automation Guy . I cannot tell why I decided to have an attribute for the list of devices rather than using the state.

The unit of measurement was taken from somewhere ™ on the internet and is of course wrong. What would you suggest?
The same applies to availability. The doc at Template - Home Assistant is not that helpful for me.

I tried to do some RTFM but the docs on defining a template sensor today, but the information I found is not exactly helpful. :neutral_face: Can you give me a pointer where I can do some RTFM?

I found the jinja code on the internet at Managing Offline Devices in Zigbee2MQTT — Home Automation Guy .
Would you be so kind and explain what you mean or show a better solution? I am a beginner when it comes to Jinja, but willing to learn

Based on your explanations, the posted Template Sensor’s configuration is the result of piecing together miscellaneous parts from various other examples. The resulting configuration doesn’t make sense but that’s its origin story.

Sorry to hear that. It’s been helpful for me and countless other users so you may wish to try reviewing it again.

FWIW, the template portion of your Template Sensor is fine (it can be optimized, but it does the job). What’s odd is its use of a unit of measurement when it has no need for it. Plus the odd use of availability which doesn’t take advantage of what that feature has to offer.

Reference

Template Sensor

1 Like

Would you like to share with me what can be optimized in the template portion of my Template Sensor? I would highly appreciate any hints on how to improve my knowledge.

The documentation on template sensors is - as far as I am concerned - rather generic. I would have loved it to see more examples beyond the “hello world” level. The example where availability: is mentioned has no explanation, the documentation of availability: later on gives a hint only.

I do have a degree in Computer Science but I have the feeling that Jinja and me are not meant to be(come) exactly best friends. Maybe it’s just that English is not my native language and the fact that I do RTFM in the evening where my understanding is sometimes ‘mildly’ challenged.

Tonight I read through the Template Sensor page again (felt like the n th time) and it made some sense, eventually.

Jinja2’s for has an optional if that allows you to reduce the number of items to iterate before entering the for-loop.

{% set result = namespace(sensors=[]) %}
{% for s in states.sensor
     | selectattr('attributes.device_class', 'defined')
     | selectattr('attributes.device_class', '==', 'timestamp')
     | selectattr('object_id', 'search', 'last_seen')
     if states(s.entity_id) == 'unavailable'
       or now() - states(s.entity_id) | as_datetime > timedelta(days=1) %}
  {% set result.sensors = result.sensors + [s.name | replace(' Last seen', '')] %}
{% endfor %}
{{ result.sensors }}

I’m not sure why your example prepended a hyphen to each sensor name followed by a newline. I omitted both in my example which produces a simple list of sensor names.

1 Like

Thank you so much Taras for showing me a better version of my cut&paste code!!! I do appreciate your effort!

I added the dash as a preparation for a persistent notification / message for Telegram as I wanted to send a dotted list of device names, the HTML would be sort of <UL><LI>device name1</LI><LI>device name2</LI></UL>.

1 Like

I suggest you maintain the attribute’s value as a simple list.

You don’t have to include dashes in the attribute’s value, you can add them later when composing the message for Telegram.

Copy-paste the following example into the Template Editor and experiment with it.

{% set x = ['cat', 'hat', 'bat', 'gnat'] %}

<UL><LI>- {{ x | join('</LI><LI>- ') }}</LI></UL>
1 Like