Home Assistant - human readable Fritz!Box uptime

1 minute read

The Fritz!Box uptime in my Home Assistant dashboard sensor looked like this:

2021-10-15T20:45:18.294Z

Super hard to read. To achieve a human readable form I had to perform a couple of steps which helped me understand HA a bit better, and serve as a good starting point for other similar actions. Here we go.

Modify configuration.yaml

To do this you can install the addon File Editor, which gives you a nice GUI for doing this.

# Configure a default setup of Home Assistant (frontend, api, etc)
default_config:

# Text to speech
tts:
  - platform: google_translate

group: !include groups.yaml
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml

# ADD THIS LINE
sensor: !include sensors.yaml

Create sensors.yaml

Note: You have to restart HA to apply those changes. At least I know no other way.

# from: https://is.gd/koYX60 and https://is.gd/VK1oDj
# this is to check if this file is actually read, go look for the "Home
# Assistant Uptime" entity in HA configuration after restarting
- platform: uptime
  name: Home Assistant Uptime

# (modified) from: https://is.gd/vfRYi3
- platform: template
  sensors:
    fritzbox_connection_uptime_human:
      friendly_name: Fritz!Box connection uptime

      # in the next line, adjust "sensor.fritz_box_6490_cable_connection_uptime"
      # according to YOUR sensor name.
      value_template: >
        {%- set up_time = as_timestamp(now())-as_timestamp(states('sensor.fritz_box_6490_cable_connection_uptime')) %}

        {% if states('sensor.last_boot') == '0.0' %}
          Soeben neu gestartet...
        {% else %}

        {%- macro phrase(name, divisor, mod=None) %}
          {%- set value = ((up_time // divisor) % (mod if mod else divisor)) | int %}
          {{- '{} {}'.format(value, name) if value | int > 0 else '' }}
        {%- endmacro %}

        {%- set values = [
          phrase('w', 60*60*24*7),
          phrase('d', 60*60*24, 7),
          phrase('h', 60*60, 24),
          phrase('min', 60),
          phrase('s', 1, 60)
        ] | select('!=','') | list %}

        {{ values[:-1] | join(' ') ~ ' ' ~ values[-1] if values | length > 1 else values | first }}
        {% endif %}