Very simple brightness adjuster for lights based on sun timings

I wanted to adjust the brightness in my automations based on time of day. The idea is that the closer to sleep time the less bright the light should be so my sleep is less disturbed. There were amazing add-ons or appdaemon scripts. Way too complex for my case though, I opted for a very simple template that I’m sharing as part of the automation below.

alias: Example automation
description: ""
  - platform: state
      - binary_sensor.person_occupancy_x
    to: "on"
  - variables:
      v_brightness: >
        {% set hours_to_sunset = (((state_attr('sun.sun', 'next_setting') | as_timestamp - utcnow().timestamp()) / 3600) | round | int) %}
        {% set hours_to_sunrise = (((state_attr('sun.sun', 'next_rising') | as_timestamp - utcnow().timestamp()) / 3600) | round | int) %}
        {% if 'above' in states('sun.sun') %} 100
        {% else %} {{ max(10,(min(12.5,hours_to_sunrise) * 8 | int)) }}
        {% endif %}
  - service: light.turn_on
      brightness_pct: "{{ v_brightness }}"
      entity_id: light.light1
mode: single

The key line is

{{ max(10,(min(12.5,hours_to_sunrise) * 8 | int)) }}

Make sure you adjust to your needs. This version keeps brightness at 100% until up to 13 hours to sunrise, then decreases it by 8% per hour to a minimum of 10% brightness. hours_to_sunset doesn’t do anything in this case, I’ve included it in case I use it (or you might want to use it) in another similar calculation.

I hope this saves an hour or two for someone who’s trying to do a similar simple brightness adjustment.