How do you use time?

My goal is to pass a HA timer attribute finishes at to a ESP and use the UNIX time in the ESP to calculate how many minutes and seconds there is left.

But I just can’t make it…


says:
time:
  - platform: sntp
    id: sntp_time

and slightly further down:

auto time = id(sntp_time).now();

But where do I place that? I get errors where ever I place it.

I also tried to output the sntp_time:

it.printf(0, 120, id(my_font_small), id(sntp_time).state);
it.printf(0, 120, id(my_font_small), id(sntp_time).now());
it.printf(0, 120, id(my_font_small), id(sntp_time).timestamp());

but none of them works.
I believe I need to use the timer sensor (it.printf(0, 160, id(my_font_small), "%.0f", id(david).state);, works) and subtract the current timestamp and it.strftime it to mm:ss.

My first attempt was to do the calculation to a sensor in HA and pass that to ESP but it only updated once a minute, so I figured I need to do the calculation on the board and.

If you are using HA (I don’t) - I believe that you don’t need the SNTP component. Just the HA time component instead.

If you are using SNTP, note that you have to wait for it to do its first lookup before you get anything valid.

Here is an example from my own config that updates a systime text sensor and outputs to MQTT every 60 sec:

time:
  - platform: sntp
    id: sntp_time
    timezone: Europe/London

   # Template Text Sensor Timestamp - Output by Interval below - https://esphome.io/components/text_sensor/template.html
   # Requires sntp_time component. Defined in common.yaml
  - platform: template
    id: systime
    lambda: |-
      char str[25];
      time_t currTime = id(sntp_time).now().timestamp;
      //strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", localtime(&currTime));
      strftime(str, sizeof(str), "%Y-%m-%dT%H:%M:%S.000Z", gmtime(&currTime));
      return (std::string) str;

interval:
  # Run every ${publish_interval} but only if MQTT is connected, publish updated/updated_by/wifi-channel to MQTT
  #- <<: !include intervals/mqtt_connected.yaml
  - interval: ${publish_interval}
    then:
      - wait_until:
          mqtt.connected:
      - mqtt.publish:
          topic: $mqtt_prefix/status/updated
          payload: !lambda |-
            return id(systime).state;
      - mqtt.publish:
          topic: $mqtt_prefix/status/updated_by
          payload: $upper_devicename/ESPHome
3 Likes

I managed to get the sntp time to work. Thank you!
But the timestamp updates too seldom. It seems like it’s once a minute or perhaps less.
I would need to get down to somewhere 2-5 seconds, not more than that.

I think you control that in your sensors. So you can change the update interval for a sensor. Certainly if you put a formatted timestamp onto a display output, it is perfectly happy updating per second. I’ve also changed my default interval from 60s to 50s to fit in with my other sensor platforms.