Unreliable Condition in Automation

I’ve put together an automation that works sometimes, but more often, it does not.

Here’s what I’m trying to do:
I have an IR distance sensor attached to my garage door opener that measures the distance to the next object downwards. Based on that information I set the status to either ‘Car in Garage’ or ‘Garage Empty’ for sensor.garage_status

When the status of that sensor changes, I store the date and time of the change in a helper called input_datetime.garage_status_last_change

I want a smart switch to turn off the garage light when I remove the car from the garage and (within 45 seconds) close the garage door.

This is how I’m trying to achieve this:

alias: Garage Lights Off when Car Removed and Door Closes
description: ""
trigger:
  - platform: state
    entity_id:
      - cover.garage_door
    from: open
    to: closed
condition:
  - condition: template
    value_template: >
      {{  as_timestamp(now()) - as_timestamp(states('input_datetime.garage_status_last_change')) < 45}}
  - condition: state
    entity_id: sensor.garage_status
    state: Garage Empty
action:
  - service: switch.turn_off
    data: {}
    target:
      entity_id: switch.garageswitch_1
mode: single

Sometimes the light turns off, but more often than not it doesn’t.

In the failing cases the trace shows that the templated time condition {{ as_timestamp(now()) - as_timestamp(states('input_datetime.garage_status_last_change')) < 45}} is showing up as ‘false’.

Do I need to build the condition differently or is that just not a reliable way to do it at all?

Use the garage status as your trigger and employ a wait-for-trigger action:

alias: Garage Lights Off when Car Removed and Door Closes
description: ""
trigger:
  - platform: state
    entity_id: sensor.garage_status
    to: Garage Empty
    from: Car in Garage
condition: []
action:
  - wait_for_trigger:
    - platform: state
      entity_id: cover.garage_door
      from: open
      to: closed
    timeout: "00:00:45"
    continue_on_timeout: false
  - service: switch.turn_off
    data: {}
    target:
      entity_id: switch.garageswitch_1
mode: single

Thanks, I’ll give it a try!
This would allow me to get rid of the helper construct with the input_datetime as well :+1:

Finally tried it and it seems to work fine - can’t see the ‘Solution’ tick box here, though, to mark it accordingly :astonished: