How to calculate / subtract two date.time from eachother?

Ok, not sure how those attributes are formatted in the first place.
If you remove the “| int” will that give you another non 0 value?

sorry, that just gives “none”

i think the “time” values are maybe just a string? thehy show as just “13:39” for example?

I found this in another thread.

{% set time = "12:45" %}
{{ (((as_timestamp(strptime(time, "%H:%M"))) - as_timestamp( strptime( now().strftime("%H:%M"), "%H:%M") )) /60) | int}}

It seems to work to calculate a time in string format.

Maybe you can replace “time” and “now” with your sensor attributes?

1 Like

This will give you the time in minutes (143) between kickofftime and finishtime.

{% set kickofftime = "10:45" %}
{% set finishtime = "13:08" %}

{{ (((as_timestamp(strptime(finishtime, "%H:%M"))) - as_timestamp(strptime(kickofftime, "%H:%M") )) /60) | int}}
3 Likes

Hi I’ve just stumbled upon this thread as I’m trying to do something similar to what OP was doing with working out a departure time. I’ve got the added complication of a TTS automation though.

This thread has been fantastic with figuring out the template for what I want, and I’ve got it to generate a departure time that’s definitely correct, but when I put it into TTS, it will say “…you should set off before x hours, y minutes, zero seconds”.

Here’s the function I use to calculate the departure time:
{{ strptime('08:00', '%H:%M') - strptime(states.sensor.time_to_work.state, '%M') }}

Now how do I separate out the hour and minute values so I can then insert them into the TTS string and make it say “…you should set off before y minutes past x”?

Just tacking onto this thread with a quick question.
The above solutions all use attributes, but I need a state (hours between now and forecast), but below does not resolve

{{as_timestamp(states('sensor.openweathermap_forecast_time')) - as_timestamp(now()) | timestamp_local  }}

gives

TypeError: unsupported operand type(s) for -: 'float' and 'str'

However

{{as_timestamp(states('sensor.openweathermap_forecast_time'))  | timestamp_custom("%H") }}

Results in the hour, expected because forecast_time is a timestamp…

{{states('sensor.openweathermap_forecast_time') | as_datetime - now() }}

results in 0:31:59.997861
Even tried using strptime, no joy

What about


{% set n = as_timestamp(now()) %}
{% set x = as_timestamp( states('sensor.openweathermap_forecast_time') ) %}
{% set t = (n-x) |timestamp_custom('%R') %}
{{ t }}

1 Like