Timestamp wrong calculation

Hello. I need to calculate the difference between the timestamp ha and the sensor. when I do that, it doesn’t calculate correctly.

{{now()}}
{{states('sensor.car_gps_sensor')}}

{{as_timestamp(now())}}
{{as_timestamp(states('sensor.car_gps_sensor'))}}

{{as_timestamp(now()) - as_timestamp(states('sensor.car_gps_sensor')) }}

Result:

2023-03-28 07:45:10.787548+03:00
2023-03-28 07:44:37

1679978710.787624
1679989477.0

-10766.212297916412

After the time conversion, there are more seconds on the gauge than on the main time. I don’t understand why this is happening.

Your second datetime doesn’t have a timezone, but I’m assuming it’s local time for you. Use the as_local filter to give it one.

{{ states('sensor.car_gps_sensor') | as_local }}

Timestamps are all measured from the same epoch: Compare the timestamps of now() and utcnow().

So, a datetime without a timezone will be assumed timezone 0 (or then UTC), and you will be out by the timezone difference, because the timestamp’s conversion will happen on the wrong time.

1 Like

Try this:

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