Button Last triggered

Hello,
as im pretty new with home assitant im struggling a bit.

I have an automation in which I want to create condition which checks when the entity “button.pc_brandon_sleep” was last triggered. If it was triggered in the last 30 minutes then my action should happen.
If someone could help me i would be very happy!

Use a Template Condition in your automation.

alias: your automation
trigger:
   ... your trigger(s) ...
condition:
  - condition: template
    value_template: "{{ states('button.pc_brandon_sleep') | as_datetime > now() - timedelta(minutes=30) }}"
action:
  ... your action(s) ...
  • A button’s state value is a datetime string.
  • We can convert it to a datetime object using as_datetime.
  • Now that it’s a datetime object, we can compare it to another datetime object.
  • now() reports the current date and time as a datetime object.
  • We can subtract 30 minutes from now() using a 30-minute timedelta object defined like this timedelta(minutes=30)
  • Finally we test if the value of the button’s datetime object is within the last 30 minutes like this:
    {{ states('button.pc_brandon_sleep') | as_datetime > now() - timedelta(minutes=30) }}

Reference

Templating

Okay that worked that k you very much!
Can i also use this Template for any Sensor by just replacing the buttton.pc_brsndon_sleep?

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 has been resolved. This helps users find answers to similar questions.

For more information about the Solution tag, refer to guideline 21 in the FAQ.

Yes. The states() function is designed to report an entity’s current state value. All you need to do is simply provide the function with the entity’s entity_id.

1 Like

I also have another question. Is it possible to change the timedelta from minutes to seconds? Would be useful for antoher automation of mine. I tried around a bit but it wont work.

Yes. Not only seconds but other units of time as well.

Python timedelta object

Oh thats nice i tried some things but it didnt work and i could find anything online by searching it specifically. But it works now so thanks a lot again!