Could you please help me converting uptime sensor output(second) to date format on ESPHOME?

Howdy,

I used this code for converting data to date format in homeassistant.

For example on sensor of homeassistant,

- platform: uptime
  name: "HA Uptime"
  unit_of_measurement: minutes

- platform: template
  sensors:
   ha_online:
      friendly_name: "HA Online"
      unit_of_measurement: "time"
      value_template: >-
# I used 'time' as seconds on purpose
        {% set time = (((states.sensor.ha_uptime.state) | round ) * 60 | int) | int %}
        {% set minutes = ((time % 3600) / 60) | int %}
        {% set hours = ((time % 86400) / 3600) | int %}
        {% set days = (time / 86400) | int %}
        {%- if time < 60 -%}
          {{ time }}
        {%- else -%}
          {%- if days > 0 -%}
            {{ days }}d
          {%- endif -%}
          {%- if hours > 0 -%}
            {%- if days > 0 -%}
              {{ ' ' }}
            {%- endif -%}
            {{ hours }}h
          {%- endif -%}
          {%- if minutes > 0 -%}
            {%- if days > 0 or hours > 0 -%}
              {{ ' ' }}
            {%- endif -%}
            {{ minutes }}m
          {%- endif -%}
        {%- endif -%}

It works very smoothly.
i.e) 150,000 seconds => 1d 17h 40m

With above code, I applied it to esphome like the below,

sensor:
  - platform: uptime
    name: "d1mini Online"
    filters:
      - lambda: !lambda |-
          int ontime = x;
          int minutes = ontime * 60;
          int hours = ontime * 3600;
          int days = ontime * 86400;
          str ontimed = " ";
          str ontimeh = " ";
          str ontimem = " ";
          if (ontime < 60) {
            return ontime;
          } else { 
            if (days > 0) {
              ontimed = str(days)  
            }
            if (hours > 0) {
              ontimeh = str(hours)
            }
            if (minutes > 0) {
              ontimem = str(minutes)
            }
            return ontimed + ontimeh + ontimem;
          }
   update_interval: 60s

But It didn’t work at all.
I know something was wrong.
Could you please correct me? I don’t know how to.
Thanks in advance.

1 Like

did you find a solution in the meantime ?

Uptime sensor in hours or days? check if this helps

1 Like

thanks, I’ll try it