Template sensor state "unknown" while template resolves correctly

I have defined this template sensor to check when a motion was last detected.

template:
  - sensor:
      last_motion_detected_loc_2:
        friendly_name: Laatste beweging Locatie 2
        value_template: >
          {% if states.binary_sensor.locatie_2_pir_sensor.last_updated is unknown %}{{"00:00:00"}}
          {% else %} {{ as_timestamp(states.binary_sensor.locatie_2_pir_sensor.last_updated)|timestamp_local }}
          {% endif %}
        unit_of_measurement: 's'

The template resolves correctly under dev_tools, giving me the following string “2023-10-11T09:12:02.671519+02:00”

sensor.last_motion_detected_loc_2 results in state “unknown”.

:exploding_head:

That should have generated quite a few errors in your log. You have mashed together the old and new template sensor formats. Should be:

template:
  - sensor:
      - name: Laatste beweging Locatie 2
        unit_of_measurement: 's'
        state: >
          {% if states.binary_sensor.locatie_2_pir_sensor.last_updated is unknown %}
            {{"00:00:00"}}
          {% else %}
            {{ as_timestamp(states.binary_sensor.locatie_2_pir_sensor.last_updated)|timestamp_local }}
          {% endif %}

You could also accomplish this with the following template:

        state: >
          {{ as_timestamp(states.binary_sensor.locatie_2_pir_sensor.last_updated, 0)|timestamp_local }}

The second parameter, “0”, passed to as_timestamp() will be substituted as the default if there is no valid datetime object to convert.

Unknown is not a keyword, not sure how this template is working at all. That would error.

Yeah I did not look too closely after they said it was working in the editor. The second option I posted should work.

It will expect a numeric state with unit_of_measurement: s, not a datetime string.

This would work

state: >
          {{ as_timestamp(states.binary_sensor.locatie_2_pir_sensor.last_updated, 0) }}

Indeed. For some reason the UOM was not causing any troubles in the past but along the way of HA’s frequent upgrades over the past year this caused the issue. Removing it solved the problem. Thanks.