Timer since i've pressed a button

I hope you can help me with a project:
I’d like to see how long it’s been since I’ve pressed a button.

I’m planning an irrigation control. If I manually activate a switch, I would like to activate a kind of timer that counts until I turn the switch off again.

Any idea?

Use the last_changed attribute of your switch or start a timer.

The problem you may run into is HA restarts. I think it would be better to save a timestamp in an input_number (whose value will be restored across restarts) when you activate the switch. Then you can tell how long it has been by subtracting that from the current timestamp. The details will probably depend on exactly what you’re trying to do, since your description is somewhat vague.


- alias: record time when switch is activated
    platform: state
    entity_id: switch.xyz
    to: 'on'
    service: input_number.set_value
    entity_id: input_number.switch_activated
      value: "{{ as_timestamp(now()) }}"

Then when you want to know how long it has been:

{{ as_timestamp(now()) - states('input_number.switch_activated')|float }}

BTW, you may be tempted to use an input_datetime for this. Don’t, they’re a pain to use!

Yeah this is a pain and never going to be fixed apparently.

I have two instances where this affects the runtime of devices and will take your advice and use the input_number method.

1 Like

Use the timer helper, this one will re-start after a boot from HA

It did not do that three years ago when this post was written, but yes that is now a valid option.