How to measure the longest time of a sensor stayed on/off?

i have a filament sensor for 3d printing. it flickers back n forth (on/off) throughout the day.
how to know how long it gets stuck in the On position? usually in seconds. i am only interested in the longest time it stayed on. so if in the day, it stayed on 8s, 20s, or 3s, i just want to know the value of 20s.
once i know, then i can implement the same for the Off position. thank you!

or is there a way i can export this entity’s activity to an Excel file? that way, i can do basic math of begin time minus end time in a new column T. sort column T to see the biggest time.

This might send you down the right path, but may not be exactly what you need since I don’t know if you will get seconds out of it - History Stats - Home Assistant

i am afraid that does not work. i think the best is to export from the SQL lite to see the start and stop time.
sadly, i have no idea what to put in this query. any idea?