How to get the difference in time between now and a sensors in a template

I have a sensor that uses a timestamp to report the last time the state changed.

I want to be able to check if more than 300 seconds has passed or if less than 20 seconds has passed.

device_class: timestamp
icon: mdi:clock-time-three-outline
friendly_name: DERP-PC_lastactive

These templates output the following values

{{as_timestamp(now())}}
{{as_timestamp(states('sensor.derp_pc_lastactive'))}}

1689984611.186536
1689984612.0

I have this exact same setup and its very simple.

Convert both to int and subtract the sensor time from now. Test if the result is greater than or equal to 300.

{{as_timestamp(now())| int - as_timestamp(states('sensor.dimitris_pc_lastactive')) | int >= 300}}

Do the same for the other check of less than 20 secs.

{{as_timestamp(now())| int - as_timestamp(states('sensor.dimitris_pc_lastactive')) | int <= 20}}

If you want to combine it it would be like this:

{{as_timestamp(now()) | int - as_timestamp(states('sensor.dimitris_pc_lastactive')) <= 20 or as_timestamp(now()) | int - as_timestamp(states('sensor.dimitris_pc_lastactive')) >= 300 }}
3 Likes

Thank you so much, I don’t know why I didn’t think to just pipe it to int

Thats quite alright. Could you just mark my comment as the solution? It will help people find it in the future :slight_smile:

1 Like