Problem with a template sensor

Hi therre. I found a code snippet i thought i could change a bit, and reuse. But i get state unavailable i HA. Is there anyone who can point me in the right direction?

##Hente dag/kveld/helg strømpris
  - platform: template
    sensors:
      nettleie_akt:
        friendly_name: 'Aktuell nettleie'
        value_template: >
          {% set dag = states('sensor.ke_nettleie_dag') | float %}
          {% set kveld = states('sensor.ke_nettleie_kveld_helg') | float %}
          {% set hours =  [[0,600,kveld],
                          [601,2200,dag],
                          [2201,2359,kveld]] %}
          {% set t = states('sensor.time').replace(':','')|int %}
          {% for h in hours if h[0] <= t <= h[1] %}
              {{h[2]}}
          {% endfor %}

If you’re getting “unavailable” it may be because you are missing defaults on your float and int filters or one of your referenced sensors could be undefined…

Another way to do this would be:

  - platform: template
    sensors:
      nettleie_akt:
        friendly_name: 'Aktuell nettleie'
        value_template: >
          {% set dag = states('sensor.ke_nettleie_dag') | float(0) %}
          {% set kveld = states('sensor.ke_nettleie_kveld_helg') | float(0) %}
          {% set sched = {
          today_at() < now() <= today_at("6:00"): kveld,
          today_at("6:01") < now() <= today_at("22:00"): dag,
          today_at("22:0") < now() <= today_at("23:59:59"): kveld
          }%}
          {{ sched.get(True)}}

FWIW, you are using the legacy template sensor format which will still work, but is no longer the preferred method.

To debug this, use Developer Tools / Template, and paste the template code into there. It appears to just be selecting day and night rate: you might find this easier:

value_template: "{{ states('sensor.ke_nettleie_dag')|float(0) if 6 < now().hour < 22 else states('sensor.ke_nettleie_kveld_helg')|float(0) }}"

Or even shorter:

value_template: "{{ states('sensor.ke_nettleie_'~('dag' if 6<now().hour<22 else 'kveld_helg'))|float(0) }}"

Thanks :slight_smile: i will look into it :slight_smile: