Preserving last valid state of a sensor before "unknown"

Hi, I know this has been asked several times, but none of the solutions seems to work in my case.

I have an Ambient Weather sensor stat sends last_rain datetime whenever it rains, but became “unknown” when it stops raining. It does not make much sense, but I have to deal with it.

I created this sensor


- sensor:
    - name: "Melcany Last Rained"
      unique_id: melcany_last_rained
      state: >
        {% if states('sensor.melcany_last_rain') not in ['unavailable', 'unknown'] %}
          {{ as_timestamp(states('sensor.melcany_last_rain')) | timestamp_custom('%d.%m.%Y') }}
        {% else %}
          {{ as_timestamp(states('sensor.melcany_last_rained')) | timestamp_custom('%d.%m.%Y') }}
        {% endif %}

The problem is that it only shows the date when the sensor.melcany_last_rain updates, otherwise it is “unavailable”.

How can I get it to show the last valid date?

- sensor:
    - name: "Melcany Last Rained"
      unique_id: melcany_last_rained
      state: >
        {% if has_value('sensor.melcany_last_rain') %}
          {{ as_timestamp(states('sensor.melcany_last_rain')) | timestamp_custom('%d.%m.%Y') }}
        {% else %}
          {{ this.state }}
        {% endif %}

Wow…seems to be working!

1 Like