Old noob needs some help with time display, days and hours instead of seconds

Hello, I have a sensor (entity) that returns remaining time of battery charge in seconds and I’d like to see it in days and hours, exactly in this format: 3d 17h
Above is an example, but just one space between 3d and 17h, and no space between the number and d or h.
I have tried to locate some help by searching forums, but closest I got was with this:

- platform: template sensors: battery_to_go: value_template: {%- set uptime = states.sensor.victron_system_battery_time_to_go.state | round -%} {%- set sep = ' ' -%} {%- set TIME_MAP = { 'd': (uptime / 86400) % 7, 'h': (uptime / 3600) % 24, } -%} {%- for unit, duration in TIME_MAP.items() if duration >= 1 -%} {%- if not loop.first -%} {{ sep }} {%- endif -%} {{ (duration | string).split('.')[0] }} {{ unit }} {%- endfor -%} {%- if uptime < 1 -%} charge {%- endif -%}

But this code above is giving me a space between the number and a letter, so it looks like this 3 d 17 h , while I want 3d 17h .
One other thing I don’t know is what to do with this code, do I just paste it into my configuration.yaml file? That didn’t seem to work, I was getting errors.
I’m new to all this so any help is very much appreciated.

You are very close! Jinja interprets spaces literally, so you have to remove the space here: {{ (duration | string).split('.')[0] }} {{ unit }} so that the duration and unit blocks are together, like this: {{ (duration | string).split('.')[0] }}**NO SPACE HERE**{{ unit }}

You can add this code in your configuration.yaml (or in a separate file if you use the !include directive to load separate yaml files), the (new) preferred way of adding templated sensors looks like this:

template:
  - sensor:
      - name: battery_to_go
        state: >
          {%- set uptime = states('sensor.victron_system_battery_time_to_go') | round -%}
          {%- set sep = ' ' -%}
          {%- set TIME_MAP = { 'd': (uptime / 86400) % 7, 'h': (uptime / 3600) % 24, } -%}
          {%- for unit, duration in TIME_MAP.items() if duration >= 1 -%}
            {%- if not loop.first -%}{{ sep }}{%- endif -%}
            {{ (duration | string).split('.')[0] }}{{ unit }}
          {%- endfor -%}
          {%- if uptime < 1 -%} charge {%- endif -%}

Side note: states('sensor.victron_system_battery_time_to_go') is better to use than states.sensor.victron_system_battery_time_to_go.state, because it does not throw any errors when the sensor isn’t loaded yet, for instance during HomeAssistant startup. Has helped me reduce a lot of errors in the logs. :smiley:

Hope this helps!

1 Like

That did it, thank you !
Now next thing is where do I place this code? I’ve tried to paste it into my configuration.yaml, but that threw an error. What’s the best way to use this?

Never-mind, I got it to work, thanks again !!!

1 Like