Template with switch last changed time

I have a switch.620_clean that controls my roomba.
I would like create a template that holds the last time roomba cleaned.

I create this template:

  - platform: template
    sensors:
      time620clean:
        value_template: >-
          {%- if is_state("switch.620_clean","on") %}
           {{as_timestamp(now()) | timestamp_custom('%d %b %H:%M', true) }}
          {%- endif %}

It works when the switch goes to “on” but it lose his value when the switch goes off.
How can I preserve it?

try this:

- platform: template
  sensors:
    time620clean:
      value_template: >-
        {% if is_state("switch.620_clean","on") %}
          {{as_timestamp(now()) | timestamp_custom('%d %b %H:%M', true) }}
        {% else %}
          {{ states.sensor.time620clean.state }}
        {% endif %}

That way if the switch state isn’t ‘on’ it will just use the last value of the sensor.

I hope that works. I haven’t tested it.

For the record… this do not work for HA 0.103

I am still using it on 0.103.5 and it works perfectly.

Yeah, my templates that use that are still working fine.

So you’ll need to be more specific on what “this do not work” means.

@finity @boggiano you are right, the templates still work, I had a typo in my code.

There is a catch, although. The sensor will be evaluated during all the time the switch is in the “on” state, so it will be showing the last time the switch sensor was on.
For example, if the switch was ‘on’ from 8:00 AM to 11:30 AM, the template sensor will display 11:30 am. That behavior did not work for me, I need to know the time it was turn from “off” to “on”.