Help with getting time 1 hour before sunset

I am looking for a way to get the time one hour before sunset. My goal is to see if the the current time is between sunset - 1 hr and sunset. For the sake of readability, I want to avoid templating as much as possible. Simply put, I want it to look something like this, if possible:

- condition: time
      after: sensor.sun_next_setting - 1hr
      before: sensor.sun_next_dusk

Is there a way to create a helper for example to give me the time for that day sunset - 1hr?

1 Like
- condition: sun
  after: sunset
  after_offset: "-01:00"
  before: sunset

Thanks, but the time should be between sunset -1hr and dusk. Dusk is usually 30-45 minutes after sunset.

  - sensor:
      - name: "Sunset Offset"
        device_class: timestamp
        state: >
          {{ (states('sensor.sun_next_setting') | as_datetime - timedelta(hours=1)).isoformat() }}

Should I create this as Helpers > Template > Sensor? I get a value, but in my automation I can’t select the helper in my condition between two different times.

I also get a value and it appears in the list of available entities for use in the Time Condition.

Did you create the Template Sensor exactly as shown above (including the line with device_class)?

1 Like

I got it working. Device type wasn’t set to timestamp.

For future reference, the inclusion of device_class: timestamp is important because it identifies it as being a Timestamp sensor. Without it, it’s a regular sensor and even if it has a proper date and time value, it can’t be used in a Time Condition (as you have already discovered).

Do you mean inside the template code? Because right now I don’t have device class in there. I selected timestamp. Is that what you mean?

No, in its YAML configuration.

device_class is an option of a Template Sensor’s YAML configuration (it’s never part of its template which is used in the state option).

If you create the suggested Template Sensor via the UI then only a few of a Template Sensor’s many options are available in the form. Fortunately, device_class is one of them and it appears as the Apparatklasse field in your screenshot. You chose timestamp (tijdstup) which is effectively the same as device_class: timestamp if you had defined the Template Sensor using YAML.

1 Like