Time difference between previous sensor update

I want to measure the time difference with milliseconds accuracy between the previous sensor state and the upcoming one. Or to put it in another way: i need the time delta of the last 2 sensor states.

What I’m trying to accomplish with this is:

I have a Tasmota with a photodiode attached as a counter and hooked up to my energy meter which blinks 1600/kwh. I can measure the consumption, but i’d also like to measure momentary wattage.

For this I need to convert kwh to w, and for that i need the time difference of the 2 measurement points.

I tried to fiddle with as_timestamp(now()) and i’m getting results by subtracting some values from each other, but i’m getting nowhere meaningful values which i can incorporate in what i want to accomplish.

I would have thought, from an accuracy point of view, that you’d be better off performing the calculation on the Tasmota flashed device and then passing the result to HA.

I know this could be done with ESPHome but I’m not familiar enough with Tasmota to suggest how.

I suggest creating a Trigger-based Template Sensor.

The following example, it reports the time delta of the state-changes of a motion sensor.

  - trigger:
      - platform: state
        entity_id: binary_sensor.foyer_motion
        from: 'off'
        to: 'on'
      - name: Motion Time Delta
        state: '{{ (trigger.to_state.last_changed - trigger.from_state.last_changed).total_seconds() }}'

The initial value will be unknown and will report a numeric time delta (in seconds) after it is triggered.


To and from, duh.
I had like 50 tabs open about templating and what not and the solution is ever so simple.

Works perfectly, thank you very much.

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic is resolved. This helps other users find answers to similar questions. For more information, refer to guideline 21 in the FAQ.