Pass value to sensor template from lovelace card or datepicker?

I have a few templates with calculating hours and costs from history stats.

Is there a way of creating a parameter for the month value and passing in a value from the HA lovecard (drop-down or datepicker for example)?
How would I achieve this? It is the month= that I would like to pass a value into to change it when needed after each month rolls over or whenever needed. Date range is when the electricity meters are read.

Dates are currently hard coded under the sensor yaml.

  - platform: history_stats    
    name: Downstairs Heating Monthly
    entity_id: switch.sonoff_1000907bc4
    state: 'on'
    type: time    
    start: '{{ now().replace(month= 8, day=11 ,hour=0, minute=0, second=0) }}'
    end: '{{ now().replace(month= 9, day=10 ,hour=0, minute=0, second=0) }}' 

create input numbers and use them in the template

"{{ now().replace(month=states('input_number.month') | int, day=11 ,hour=0, minute=0, second=0) }}"

alittle easier to read:

start: >
  {% set month = states('input_number.month') | int %}
  {{ now().replace(month=month, day=11 ,hour=0, minute=0, second=0) }}
2 Likes

Brilliant petro thanks.

I’ll have a shot at implementing that.

I’m implemented this and restarted but changing the input numbers from a new entity on lovelace doesn’t change anything. Do I need to restart HA each time I change one of the input numbers to pass in the new value?

sensor yaml:

  - platform: history_stats    
    name: Downstairs Heating Monthly
    entity_id: switch.sonoff_1000907bc4
    state: 'on'
    type: time    
    start: "{{ now().replace(month=states('input_number.start_month') | int, day=11 ,hour=0, minute=0, second=0) }}"
    end: "{{ now().replace(month=states('input_number.end_month') | int, day=10 ,hour=0, minute=0, second=0) }}"   
   

config yaml:

input_number:

  start_month:
    name: Start Month
    initial: 8
    min: 1
    max: 12
    step: 1
    mode: box
    
  start_day:
    name: Start Day
    initial: 11
    min: 1
    max: 31
    step: 1
    mode: box  
    
  end_month:
    name: End Month
    initial: 9
    min: 1
    max: 12
    step: 1
    mode: box
    
  end_day:
    name: End Day
    initial: 10
    min: 1
    max: 31
    step: 1
    mode: box  

Just tested it in nodered and the state changes fine with the start_month entity.

But oddly not changing the history stats data.

it’s possible that it doesn’t resolve like a normal template.

works if I simulate it in templates (developor tools) but no not dynamically.
Possibly needs a bit more work, perhaps some kind of reload script on state change (nodered maybe).

Any pointers?

Only by restarting HA does the input number update the current template with the new value. Maybe the template needs moving out of sensors and placing in another yaml than can be reloaded on a trigger state change