Time Based Automation: Trigger X amount of time before time helper (e.g. 9 hours before I wake up)

Hello Everyone! :slight_smile:

I’m new to home assistant and still learning HA and YAML. I am not great at code and learn my own ADHD way, so sorry if this is a weird workaround. I’m adding this as I noticed a lot of people were struggling with it.

I wanted to set up automations around sleeping. I started with a simple time helper input which I added to my dashboard.

Example:

Wake Up: 8:00 AM

I then wanted to set up some automations for before going to bed.

Automation 1:

Check if the Living Room TV (android tv integration) is “on” 9 hours before my scheduled wake up time (08:00:00 AM) as set by the time helper. If “yes”, then send notification to Living TV saying “Go to bed”.

Automation 2:

Trigger 8 hours before wake time and see if Bedroom TV is “on” and if “yes” send notification to bedroom TV saying “Go to sleep”.

Here is how I got it to work:

  1. Devices & Integrations > Helpers > Set up Time Helper Input

  2. Using the File Editor Addon > Add to the configuration.yaml file the following:

sensor:
  - platform: template
    sensors:
      bed_trigger_time:
        friendly_name: "Bed Trigger Time"
        device_class: timestamp
        value_template: >
          {% set wake_time = today_at(states('input_datetime.wake_time')) %}
          {% set trigger_time = wake_time - timedelta(hours=9) %}
          {% if trigger_time < now() %}
            {% set trigger_time = trigger_time + timedelta(days=1) %}
          {% endif %}
            {{ trigger_time.isoformat() }}

**I noticed you need to specify “device_class:” with “timestamp” or the automation trigger date/time based on value of sensor won’t recognize and display your new sensor. (sensor.bed_trigger_time…)

  1. Set up your automation. :slight_smile:

I hope this helps someone and please feel free to provide advice if there was a much simpler way to do this.

1 Like

I’m also just wondering how to do it, please let me know. maybe you’ll find some inspiration here

because I’m still looking so if you manage to figure it out better so let me know if it can be achieved without a template