Hello,
I have also an issue to calculate a time-differnce. I am in GNT+2 (Germany) and want to have the difference between a start-date (measured in GMT) and now (GMT+2).
I am using:
{{ (as_timestamp(utcnow())| timestamp_custom("%Y-%m-%d %H:%M:%S") |as_datetime) - (state_attr("sensor.keba_p30_charging_power", "started")|as_datetime) }}
which give me for example: 2:26:12 (2 hours, 26 min, 12 seconds), but it has to be 0 hours, 26 min and 12 seconds.
The attribute “started” of sensor.keba_p30_charging_power is “2025-04-28 06:42:17”
Any help is appreciated.
Unfortunately that does not tell us anything if we don’t know your local time.
What does this return in the template editor:
{{ state_attr('sensor.keba_p30_charging_power', 'started') }}
{{ now() }}
Also please make the effort to format your config correctly for the forum using the </>
button. Otherwise we have to mess around replacing all the fancy quotes the forum uses that are not valid in yaml
Thanks for the reply, I thought my question was clear enough. I am in Europe/Berlin, means at the moment GMT+2.The attribute is measured in GMT.
Back to you question, the result is:
2025-04-28 06:42:17.000
2025-04-28 09:47:17.744669+02:00
My calculation is:
{{ (as_timestamp(utcnow())| timestamp_custom(“%Y-%m-%d %H:%M:%S”) |as_datetime) - (state_attr(“sensor.keba_p30_charging_power”, “started”)|as_datetime) }}
What does this return?
{{ utcnow() - state_attr('sensor.keba_p30_charging_power', 'started')|as_datetime }}
The result is:
TypeError: can't subtract offset-naive and offset-aware datetimes
{{ now() - state_attr('sensor.keba_p30_charging_power', 'started')|as_datetime|as_local }}
The result is:
3:39:34.698055
which means again that the 2 hours were not substracted.
Correct answer should be here:
1:39:34.698055
Did you use utcnow()
or now()
?
Have tried both, both are showing the 2 hours.
Just to confirm - checking the state in developer-tools/states shows:
started: 2025-04-28 06:42:17.000
Checking the state in developer-tools/templates:
{{ state_attr('sensor.keba_p30_charging_power', 'started')|as_datetime|as_local }}
shows 2025-04-28 06:42:17+02:00
This one is missing a timezone indicator in the formatting, which is what gives the TypeError.
I am not sure if a %z or %Z or some of its variants can be used here.
https://www.man7.org/linux/man-pages/man1/date.1.html
Make them both offset-native
{{ utcnow().replace(tzinfo=None) - state_attr('sensor.keba_p30_charging_power', 'started')|as_datetime }}
Many many thanks- this is working !