One template sensor appears to work. Another similar one doesn't

I have a device that monitors the level of a propane tank. The entity for the tank has a number of states associated with it, which includes (among others) the battery % for the monitor and the date/time of the last measurement. If I put the following in the template editor then I see their respective values:

{{ state_attr('sensor.neviweb130_sensor_lm4110_zb', 'Last_sampling_time')}}
{{ state_attr('sensor.neviweb130_sensor_lm4110_zb', 'Battery_level')}}

The output of the above shows something along these lines:

2024-01-18 20:58:19
100

I’d like to have the above displayed in an entity card in a dashboard, so I created a couple of template sensors to help accomplish this:

template:
  - sensor:
    - name: Propane Monitor Time of Last Check
      state: >
        {{ state_attr('sensor.neviweb130_sensor_lm4110_zb', 'Last_sampling_time') }}
      device_class: timestamp

    - name: Propane Monitor Battery Level
      state: >
        {{ state_attr('sensor.neviweb130_sensor_lm4110_zb', 'Battery_level') }}
      device_class: battery

The battery level sensor appears to be working fine, but the date/time one always returns “unknown” no matter what I try. If I view the states in the Developer Tools it shows the date is in the format of “2024-01-18T20:58:19” which I believe is the correct format.

So how do I go about troubleshooting this? Am I not defining the template sensors properly?

You need the result of the template to be a datetime object. Try:

{{ state_attr('sensor.neviweb130_sensor_lm4110_zb', 'Last_sampling_time') | as_datetime | as_local }}

For future reference, you don’t need to create Template Sensors in order to display the attributes of sensor.neviweb130_sensor_lm4110_zb in the UI. The Entities card lets you display an entity’s attributes.

For example, this Entities card is configured to display the value of a climate entity’s hvac_action attribute.

In your case it would look something like this:

type: entities
  - type: attribute
    name: Last Sampling Time
    entity: sensor.neviweb130_sensor_lm4110_zb
    attribute: Last_sampling_time

As for the problem with your first Template Sensor, mekaneck is on the right track. As soon as you specify datetime: timestamp the supplied datetime should include date, time, and timezone offset.

Thanks, this worked like a charm so I’ll go with this approach.

1 Like