Hi,
Fairly new to HA. I have been trying to create an automation that Alexa announces the following message at a fixed time (say 7AM every weekday) :
Based on current travel conditions you will take mm minutes to reach, you should leave the house by hh:mm.
i am getting the travel time by
sensor.google_travel_time
to get the message for Alexa i need to do the calculation:
hh:mm (which is also fixed) - sensor.google_travel_time
e.g. 9:30 AM - 25 mins (travel time) = 9:05
i have been searching about it and looks like something like this from an old post should work:
{{strptime(“07:15”, “%H:%M”) - strptime(states.sensor.total_travel_time_now.state, “%M”) }}
however, i haven’t been able to get this to work for my use case.
{{strptime(“09:30”, “%H:%M”) - strptime(states.sensor.google_travel_time, “%M”) }}
Because there are so many different time functions, when working with them it is critical to sort out the data types you are starting with and what you want returned, so that you can choose the right functions to use.
strptime()
takes a string and a format and outputs a datetime object, any missing data needed for the datetime is filled in from the default value of 1900-01-01 00:00:00
. Your final template example is subtracting one datetime object from another datetime object, and relies heavily on the default value. It boils down to the question “How much time was between 1900-01-01 09:30:00 and 1900-01-01 00:25:00 ?”, which is returned as a timedelta object representing 9 hours and 5 minutes…
Instead, turn your desired arrival time into a datetime object with today_at()
then use timedelta()
to find the new time after subtracting the travel time.
service: notify.alexa_media_example
data:
message: |
{% set eta = '09:30' %}
{% set tr_min = states('sensor.total_travel_time_now') | int %}
Based on current travel conditions, you will take {{ tr_min }} minutes
to reach your destination. You should leave the house by {{ (today_at(eta) - timedelta(minutes = tr_min)).strftime('%H:%M') }}.
This works, thank you both for the solution and the explanation.