I have a template sensor which I put together but I am fairly certain that there must be a better way to have done it. It works but I am no python or jinja expert so I am wondering if there is any way that I have not found that would make this more elegant.
It isn’t the most important sensor in the world, it just formats sensor.uptime
whose state is a decimal number of days into a string in this format,
3 weeks, 2 days, 1 hr, 43 mins
and it really just became a learning exercise but I am interested in any improvements (I’m half expecting there to be some simple built-in function that I couldn’t find that takes the number of days and does the conversion in one line!!).
Here is my effort:
- platform: template
sensors:
ha_uptime:
friendly_name: HA Uptime
value_template: >
{% set weeks = (states('sensor.uptime') | int / 7) | int %}
{% set days = (states('sensor.uptime') | int) - (weeks * 7) %}
{% set hours = (states('sensor.uptime') | float - states('sensor.uptime') | int) * 24 %}
{% set minutes = (hours - hours | int) * 60 %}
{% if weeks == 1 %}
{% set uptime = weeks ~ ' week, ' %}
{% elif weeks > 1 %}
{% set uptime = weeks ~ ' weeks, ' %}
{% else %}
{% set uptime = '' %}
{% endif %}
{% if days == 1 %}
{% set uptime = uptime ~ days ~ ' day ' %}
{% elif days > 1 %}
{% set uptime = uptime ~ days ~ ' days ' %}
{% else %}
{% set uptime = uptime %}
{% endif %}
{% if days > 0 %}
{% set uptime = uptime ~ ',' %}
{% else %}
{% set uptime = uptime %}
{% endif %}
{% if hours == 1 %}
{% set uptime = uptime ~ hours | int ~ ' hr' %}
{% elif hours > 1 %}
{% set uptime = uptime ~ hours | int ~ ' hrs' %}
{% else %}
{% set uptime = uptime %}
{% endif %}
{% if hours | int > 0 %}
{% set uptime = uptime ~ ', ' %}
{% else %}
{% set uptime = uptime %}
{% endif %}
{% if minutes == 1 %}
{% set uptime = uptime ~ minutes | int ~ ' min' %}
{% else %}
{% set uptime = uptime ~ minutes | int ~ ' mins' %}
{% endif %}
{{ uptime }}