Ok. Did you look at Simple stopwatch?&/or Stopwatch with start/stop/resume, lap and reset?
You need two input_datetime helpers, one to store the start time and one for the stop time. Then an automation that fires when the device turns on which updates the start time helper and another automation that fires when the device turns off which updates the stop time. I combined the two automations into one with two triggers and a choose section. Last item is a template sensor whose state is ( end_time minus start_time ) if the timer is stopped, or ( now() - start_time ) if the timer is running. I threw the following together this evening. In the code below I’m using an input_boolean that I created to trigger & test it. Just replace the input_boolean with the entity_id of the switch you want to track.
templates:
- sensor:
- name: 32A Charging Timer
unique_id: 32a_charging_timer
state: >
{% if is_state("input_boolean.32a_charging_on_off", "on") %}
{{ as_timestamp(now()) - state_attr("input_datetime.32a_charging_start", "timestamp") }}
{% else %}
{{ state_attr("input_datetime.32a_charging_end","timestamp") - state_attr("input_datetime.32a_charging_start","timestamp") }}
{% endif %}
device_class: duration
state_class: measurement
unit_of_measurement: s
Automation:
alias: 32A Charging Timer
description: ""
trigger:
- platform: state
entity_id:
- input_boolean.32a_charging_on_off
id: Start
to: "on"
- platform: state
entity_id:
- input_boolean.32a_charging_on_off
id: End
to: "off"
condition: []
action:
- choose:
- conditions:
- condition: trigger
id: Start
sequence:
- service: input_datetime.set_datetime
data:
timestamp: "{{ as_timestamp(now()) }}"
target:
entity_id: input_datetime.32a_charging_start
- conditions:
- condition: trigger
id: End
sequence:
- service: input_datetime.set_datetime
data:
timestamp: "{{ as_timestamp(now()) }}"
target:
entity_id: input_datetime.32a_charging_end
mode: single
3 helpers:
And my input_boolean:
HA only updates the templated sensor once every minute but when stopped it’s to the second.
The result: