Is it possible to check how long time has a light been turned on?

I have a light group with all lights indoor, would like to make an automation to turn off any light that ion for more than x hours. Is it possible by loop through the entities and find which light has been on for x hours? Thanks

Test:

Every 1 minute ("/1") he checked.

If the light stays on for more than 2 minutes(120 ) he turns it off

alias: Turn off lights that have been on for more than 120 seconds
description: ""
trigger:
  - platform: time_pattern
    minutes: "/1"
condition: []
action:
  - variables:
      max_on_seconds: 120
  - service: homeassistant.turn_off
    target:
      entity_id: >
        {{ states.light
           | selectattr('state', 'eq', 'on')
           | selectattr('last_changed', 'lt', now() - timedelta(seconds=max_on_seconds))
           | map(attribute='entity_id') | list }}
mode: single
1 Like

That’s great, didn’t know it’s possible to poll data this way, will try to see if I can configure a template trigger based on your template!