I’m trying to create a template that returns the number of seconds between one entity state change and another entity state change, to use in a sensors.
I have this:
{{ ((as_timestamp(states.binary_sensor.test_switch_1.last_changed) - (as_timestamp(states.input_boolean.previous_drum_wash.last_changed))/3600) | round(2)) }}
However, it seems to just be returning seconds since 1970, rather than the difference between the two events.
What do I need to change?
finity
April 9, 2022, 1:17am
2
It looks like you are dividing just the last timestamp by 3600 instead of the resultant subtraction value which I assume is what you wanted
Check your parenthesis.
Thank you.
I’ve finally settled on this:
{{ (((as_timestamp(states.binary_sensor.test_switch_1.last_changed))) - (as_timestamp(states.input_boolean.previous_drum_wash.last_changed))) | round(0) }}
This returns the number of seconds between events.
Next step is the triggered template sensor, though I can’t get it to pass the config check.
- platform: template
- trigger:
- platform: state
entity_id: binary_sensor.test_switch_1
from: 'off'
to: 'on'
sensor:
- name: time_between_washes
state: "{{ (((as_timestamp(states.binary_sensor.test_switch_1.last_changed))) - (as_timestamp(states.input_boolean.previous_drum_wash.last_changed))) | round(0) }}"
finity
April 9, 2022, 3:05pm
4
that’s because you are mixing “modern” & “legacy” template sensors.
“template” is it’s own integration separate from “sensor”.
the “sensor” integration has a platform “template”.
the “template” integration doesn’t.
try this:
template:
- trigger:
- platform: state
entity_id: binary_sensor.test_switch_1
from: 'off'
to: 'on'
sensor:
- name: time_between_washes
state: "{{ (((as_timestamp(states.binary_sensor.test_switch_1.last_changed))) - (as_timestamp(states.input_boolean.previous_drum_wash.last_changed))) | round(0) }}"
see here:
Thanks again.
It’s working now.
Putting it ‘template’ instead of ‘sensor’ also makes a difference, it seems.
123
(Taras)
April 9, 2022, 3:32pm
6
For future reference, last_changed
contains a datetime object so you can perform subtraction directly. The result is a timedelta object so we can use its total_seconds()
method to get what we want. The resulting template is more concise and has no nested parentheses.
state: "{{ (states.binary_sensor.test_switch_1.last_changed - states.input_boolean.previous_drum_wash.last_changed).total_seconds() | round(0) }}"
123:
total_seconds()
That is excellent, thank you.
Is that available for total minutes too? Where in the docs would I find that?
There’s so much to templating that I don’t yet know.
123
(Taras)
April 9, 2022, 9:01pm
8
It’s python.
Python timedelta .
total_seconds()
is the timedelta object’s only method.
1 Like