I’m struggling with some time calculations on an ESP32 in ESPhome. This is for a Lilygo TDisplay S3 device.
I want to display three times: the current time, the time that a significant event happened, and how long ago did that event happen. To do this, I need to track three times, all of which are to be formatted as “HH:MM”:
- The current time of day
- A stored time of day: pressing a button should store the current time of day
- The time difference between the two times (current time is always larger than stored time.)
Getting the current time of day is easy with id(sntp_time).now()
and formatting it with strftime("$I:$M")
.
My problem comes with how to store the time, and how to calculate and format the difference. I kind-of-sort-of have it working, but I think the approach is ugly and there has to be a better way.
To store the time, I tried to use a global of type: time
but that throws an unknown type compilation error. I tried several other types (can’t remember them all.) What I’m using for now is type: int
for the global, and when it’s time to store the current time, I use id(savedTime) = time.timestamp;
from within a button.on_press lambda expression. This stores the current time as a Unix epoch time.
Then, to calculate the time difference, I get the difference in seconds with int seconds = id(ha_time).now().timestamp - id(savedTime);
. Then I use integer division and modulo math to get hours and minutes. Finally, I display them using an it.printf(..., "%2.2d:%2.2d", h, m)
call. Is there a better way?
In addition, I want HA to be able to read the three times as human readable strings. I’m currently doing this with template text sensors:
- The current time uses a lambda of
return {id(ha_time).now().strftime("%Y-%m-%d %H:%M:%S").c_str()};
- For the stored time, I’m using a string global which gets set when the time is saved, using strftime() to format the current time as a string. (When stored, the current time is saved as both a string that can be read by HA, and as an integer timestamp that can be used in subsequent calculations.)
- For the time difference, I’m struggling with how to take the difference (which I have been calculating as seconds) into a clean string that can be returned by the text sensor. I’m using snprintf() into a buffer, but I’m not thrilled with that.
So, I’m looking for advice on the best way to handle this. Basically, store a time so that it can be human readable by HA, and calculate the difference between the times that can be human readable by HA and displayed on the local LCD.