Uptime sensor in hours or days?

That should actually work. I am currently on ESPHome version 2023.3.2 and can confirm that setting a longer update interval for the template text sensor works.

The other thing to remember is (at least that’s my understanding) that even if the last restart time is sent every minute, because the value has not changed this should not be registered as an update in HA and thus not write an entry into the database.
Compare that with an actual uptime sensor that changes its value every single time, this would result in a state change and a new entry in the database.

Is it possible to make such a change so that there is no error when compiling?

Came up with this solution (dd:hh:mm:ss format):

text_sensor:
  - platform: template
    name: Uptime
    update_interval: 1s
    lambda: |-
      auto s = millis() / 1000;
      return str_snprintf("%02d:%02d:%02d:%02d", 11, s / 86400, s / 3600 % 24, s / 60 % 60, s % 60);

There’s also this version:

  #  Creates a sensor of the uptime of the device, in formatted days, hours, minutes and seconds
  - platform: template
    name: "Device Uptime"
    entity_category: diagnostic
    lambda: |-
      int seconds = (id(uptime_seconds).state);
      int days = seconds / (24 * 3600);
      seconds = seconds % (24 * 3600);
      int hours = seconds / 3600;
      seconds = seconds % 3600;
      int minutes = seconds /  60;
      seconds = seconds % 60;
      if ( days > 3650 ) {
        return { "Starting up" };
      } else if ( days ) {
        return { (String(days) +"d " + String(hours) +"h " + String(minutes) +"m "+ String(seconds) +"s").c_str() };
      } else if ( hours ) {
        return { (String(hours) +"h " + String(minutes) +"m "+ String(seconds) +"s").c_str() };
      } else if ( minutes ) {
        return { (String(minutes) +"m "+ String(seconds) +"s").c_str() };
      } else {
        return { (String(seconds) +"s").c_str() };
      }
    icon: mdi:clock-start
2 Likes

This might be a silly question but how I can use this code?

I copy/paste it into configuration.yaml, but what next? Thanks

You take it out again and instead put it where it belongs :point_down: