Jinja (Templating) help needed

Hello all

I need some help with Templating. Tried a few things but not getting anywhere.

Basically, I have an entity called somebody, that is my family. If somebody is away, I want to find out the difference between time - now and time somebody left home.

{{ (now()) - (states.binary_sensor.somebody.last_changed) }}

if the time is greater than 1 hour, then I want to perform some action.

Ca somebody help me please.

Thank you

Do the math in seconds, and check the state.

{{ is_state('tracker.somebody', 'not_home') and ( now()|as_timestamp - as_timestamp(states.binary_sensor.somebody.last_changed) > 3600 ) }}

Side-note: Both now() and an entity’s last_changed produce datetime objects. That means both have built-in timestamp() methods. We can leverage that to shrink the template a little bit:

{{ is_state('tracker.somebody', 'not_home') and
  (now().timestamp() - states.binary_sensor.somebody.last_changed.timestamp() > 3600 ) }}
1 Like

Ugh. I was messing with that earlier today and could not get it to work because I was using now().timestamp i.e. without the (). Thank you, it makes sense now.

Hi

Excellent, Thank you for your quick replies.

Sorry, just one more thing. Would you compare value like this?

{{ is_state('binary_sensor.somebody', 'off') and
  (now().timestamp() - states.binary_sensor.somebody.last_changed.timestamp() > 3600 ), 'True' }}

I want to arm the alarm automatically if no one is home for more than 1 hour. Above will be my trigger, and in action I will arm the alarm.

No. That is not a valid template. The template I posted and 123’s improved version will both resolve to true or false.