Calculating time to next sun event

Hi!

I’ve tried to make custom sensors to calculate the time till the next sun event (sunset or sunrise).
The first part I have managed to do with custom sensors, but to show it in my lovelace-dashboard I wanted it to be more human-readable.

This is where I had problems. The code I tried writing keeps giving me this error:

TemplateError(‘TypeError: unsupported operand type(s) for /: ‘str’ and ‘int’’) while processing template

The code I’m trying to use is this pasted below.
sensor.next_sun_event_sec is the previously mentioned template sensor.

  - platform: template
    sensors:
     next_sun_event_human:
      friendly_name: "Neste solhendelse"
      unique_id: "next_sun_event_human"
      value_template: >-
              {% if states('sensor.next_sun_event_sec') | float > 3600 %}
                {{ float(states('sensor.next_sun_event_sec') / 3600) | round(0) }}
              {% elif states('sensor.next_sun_event_sec') | float > 60 %}
                {{ float(states('sensor.next_sun_event_sec') / 60) | round(0) }}
              {% else %}
                {{ float(states('sensor.next_sun_event_sec')) | round(1) }}
              {% endif %}

I am kinda stuck in my own ways here, so help with this code or suggestions to do it other ways are appreciated.

The second line of the template used float in the wrong place which caused division of a string value by an integer value.

The easiest way to avoid that is by using a variable. It also helps to improve the template’s legibility.

  - platform: template
    sensors:
     next_sun_event_human:
      friendly_name: "Neste solhendelse"
      unique_id: "next_sun_event_human"
      value_template: >-
        {% set t = states('sensor.next_sun_event_sec') | float %}
        {% if t > 3600 %}
          {{ (t / 3600) | round(0) }}
        {% elif t > 60 %}
          {{ (t / 60) | round(0) }}
        {% else %}
          {{ t | round(1) }}
        {% endif %}

Wow! There we go.

Using a variable is the obvious way to go, and now I know how to.

Thank you!

1 Like

You’re welcome!

Please consider marking my post (above) with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has an accepted solution. This helps users find answers to similar questions.

1 Like