Another templating question - sorry

Sorry, I’m stuck with a templating question thats baffled me for hours.

I’m trying to get a sensor template that calculates the time since an entities state changed from ‘cleaning’ to ‘docked’.

So far, I’ve got this, which gives me the time in hours since the entity state changed, works OK, but on a reboot, it resets to zero, presumably because the state changes to unavailable or something during reboot.

value_template: "{{ ((states.sensor.time.last_changed - states.input_boolean.vaccompleted.last_changed).total_seconds() / 3600) | round(1) }}"

I only want the time since the state changed specifically from ‘cleaning’ to ‘docked’. Any suggestions?

Thank you.

Amanda

the “last_changed” attribute is lost on a reboot. there have been a few requests to change that but nothing has been addressed so far.

But that won’t really help with what you want to do anyhow.

What I would do is to create an automation that sets a datetime entity when the other entity changes from cleaning to docked so that the time survives restarts.

then you can use the timestamp attribute of the datetime entity to do other stuff in templates.

Here is an example of that:

{% set total_secs = as_timestamp(now()) - state_attr('input_datetime.both_date_and_time', 'timestamp') %}
{% set days = (total_secs / 86400) %}
{% set hours = (total_secs % 86400) / 3600 %}
{% set minutes = ((total_secs % 86400) % 3600) /60 %}
{{days | int}} days, {{ hours | int }} hours, {{ minutes | int }} minutes

which returns for datetime entity set for 11-26-202 20:29:00:

0 days, 13 hours, 5 minutes

Awesome, thanks! Knew there’d be a way :slight_smile:

Here’s what I ended up with:

- id: Vacuum Completed
  alias: Vacuum Completed
  initial_state: true
  trigger:
  - platform: state
    entity_id: vacuum.neato
    to: 'docked'
    from: 'cleaning'
  action:
  - service: homeassistant.turn_on
    entity_id: input_boolean.vaccompleted
  - service: input_datetime.set_datetime
    data:
      entity_id: input_datetime.last_vac_completed_at
      timestamp: "{{ now().timestamp() }}"

Then a template sensor:

{{ (((as_timestamp(states.sensor.time.last_changed)|float) - ((states.input_datetime.last_vac_completed_at.attributes.timestamp) | float)) / 3600) | round(1) }}

:slight_smile:

1 Like