Get sensor time elapsed on last status on notify

Hi, I have a sensor that detect when my home power from grid is down or up. I have a notification system to inform to me about the status change of that. Now, how can I put in the template system the elapsed time of the sensor on down (false) state?.
I’m currently using this template:

{{ (as_timestamp(now()) - as_timestamp(states.sensor.grid_power_live.last_changed)) | timestamp_custom("%H:%M", false) }}

But the problem with this is that when notification activate, render the template but in that time the last_changed is the new state, not the oldest state, so always send on the notification the elapsed time from the new state.
The notification that i want need to say something like “Grid Power on: elapsed time in off state: {{ template method to get that info }}

However you notice the power is down, use that in an automation to set a inout_datetime.
This can later be used for the notification

This is a good method, thanks I will use it… thanks