Calculate difference between two different times

Good afternoon!

My goal is to know the duration of an automation from the automation code itself.
At the end of your code I will therefore have to calculate:

now()-state_attr(‘automation.008’, ‘last_triggered’)
and I need it in format “HH:MM:SS”

now() is in local time
state_attr(‘automation.008’, ‘last_triggered’) is in UTC time

now()= 2023-11-27 20:47:00.069517+01:00
state_attr(‘automation.008’, ‘last_triggered’) = 2023-11-27 13:46:32.727794+00:00

{{now()- state_attr(‘automation.008’, ‘last_triggered’) }}=
6:00:27.343517

In making the difference, HA also calculated the extra UTC time.

Now i’ve a TIME STRING 6:00:27.343517 what where to turn into: 06:00:27

I then need to transform the string into a datetime format using strptime:

{{strptime(now()- state_attr('automation.008', 'last_triggered'), '%H:%M:%S.%f' }}

and then present it as you see fit:

{{as_timestamp(strptime(now()- state_attr('automation.008', 'last_triggered'), '%H:%M:%S.%f' )| timestamp_custom("%H:%M:%S")}}

The problem is that something is wrong in the transition from string to datetime.
I don’t have the date part so I only used the time part in the template: ‘%H:%M:%S.%f’

Where I’m wrong?

now()- state_attr('automation.008', 'last_triggered') returns a timedelta object, not a time string. If you want a string you have to add a string filter.

Then you could just use string slicing to remove the milliseconds.

{{ ((now()- state_attr('automation.008', 'last_triggered')) | string).split('.')[0] }}

OK thank you.
Just to understand better and give help to others who may have different interests…

I feel like I was… lucky.
Ultimately I just did a string extraction.
Let’s say I wanted the output in: “HH_MM_SS”

How was I supposed to solve it?

Time and date templates can get complicated quickly since there are so many ways the information is represented. It’s easy to lose sight of the goal and end up with something that kind-of works but is overly complicated or has a failure case that isn’t obvious at first.

If you just need a string in “HH_MM_SS" format, you could just do what I already proposed above with the addition of a replace() to swap _ for the existing :.

{{ ((now()- state_attr('automation.008', 'last_triggered')) | string).split('.')[0] | replace(':','_')  }}

There are some great time-related macro collections available that can make coversions easier:

Easy Time Macros
Relative Time Plus

And there’s always the Epic Time Conversion Thread.

OK Thanks for your attention!