Hi All. I’m having some strange issues with timestamps I’m using to calculate how long a switch has been on for. I’m sure this is easy to solve but it’s got me stumped for now.
I’m setting a trigger-based sensor with a timestamp for the on-state, and the off state. Then calculating the difference between the two points to get number of elapsed seconds. Problem is that it seems like something is going wrong somewhere. For example - I time myself triggering the on and off states of the switch for 30 seconds (or 1 second either side of that) and I get the following timestamps.
On Timestamp: 1671411497.977381
Off Timestamp: 1671411499.400326
Diff between the two is ~1.422 - which means 1.422 seconds. Right?
So either HA is taking a long time to set the sensor values and I’m losing ~29 seconds somewhere due to latency or I’m reading this incorrectly.
Here is my trigger sensor:
- trigger:
- platform: state
entity_id: switch.wx8_107_zone
to: "on"
sensor:
- name: "Zone_On"
state: "{{ now().timestamp() }}"
unit_of_measurement: "Seconds"
- trigger:
- platform: state
entity_id: switch.wx8_107_zone
to: "off"
sensor:
- name: "Zone_Off"
state: "{{ now().timestamp() }}"
unit_of_measurement: "Seconds"
Example Calculation:
{{ (((states('sensor.Zone_Off')| float-states('sensor.Zone_On')| float))/60)|string + 'minutes'}}