Support templates for tod before and after properties

I would like to be able to create a tod binary sensor with after and/or before times coming from helpers, which requires a template. Currently, before and after must be only string or time. An example of what I am trying to achieve:

- platform: tod
  name: High cost time
  after:  '{{ states("input_datetime.start_time") }}'
  before: '{{ states("input_datetime.end_time"  ) }}'

where start_time and end_time are Date and/or time helpers.

This will allow me to define High cost time once rather than in each script/automation.

You could accomplish this with a template binary sensor. Like this:

template:
  - binary_sensor:
      - name: "High cost time"
        state: >
          {% set t_now = now().strftime("%H:%M") %}
          {% set t_on = states('input_datetime.start_time') %}
          {% set t_off = states('input_datetime.end_time') %}
          {{ t_on <= t_now <= t_off }}

This is assuming your input_datetimes are time only and don’t contain a date. You can adjust srftime() if they contain a date.

Thank you, @tom_l. I received a similar suggestion from @petro in a different thread which I reposting here in case anyone else runs into a similar challenge.

template:
  - binary_sensor:
    - name: Energy Savings Period
      state: >
        {{ today_at(states("input_datetime.energy_savings_start_time")) < now() < today_at(states("input_datetime.energy_savings_end_time")) }}

I consider myself to be a pretty competent coder but, as I am not that familiar with Python or Jinja2, I find myself struggling with things that should be easy. I do appreciate the support from everyone in the community.

I keep forgetting about today_at(). It is a neat solution. Wouldn’t expect anything less from petro.

I too have been trying to figure out how to programmatically set the before and after times on a ‘tod’ sensor. Shame the sensor can’t be used this way. We’ll always find new uses-cases :slight_smile:
Thanks for the question, and excellent replies.