I have a problem with the calculation of times and durations in templates and have been trying to find a solution for hours without success.
Starting position:
I have a sensor for public transport that outputs the arrival time at the destination as a string in the format HH:MM. It also gives me the current delay at the destination as an integer in minutes.
In a template, I would now like to add both values to a time in order to create a message in the sense of “the expected arrival time is HH:MM”.
That worked, thanks for the quick help! Now I just have to find out why it works.
By the way, the first line in your example code is missing a “)” at the end of the line. Just in case someone has the same problem in the future and looks at your solution.
Thanks for bringing the mistake to my attention. I have corrected it in the example posted above.
The template for arrival_datetime uses today_at to convert the arrival time, which is a string value, to a datetime object where the date is set to today and the time is the arrival time.
The template for delayminutes uses timedelta to convert the delay time, which is a numeric string value representing minutes, to a timedelta object.
Adding the datetime object with a timedelta object produces a datetime object (that’s been incremented by the amount of the timedelta object). It displays the computed time and date (but in the format of a datetime object).
The final template simply displays the computed datetime object as a time string only.
Thank you very much for your explanation!
My mistake was to assume that datetime objects can be added together. This is obviously not the case and you can only add datetime objects with timedelta objects. Did I understand that correctly?