How to capture event time duration based on two condition

Hi guys
I currently have a tag that indicates the machine is off or on. How can I capture the duration between the event of on and off. For example, I turned off this machine at 2.30PM and turned on the machine at 2.45PM , I shall let a tag record this duration which is 15 minutes.
Just wondering how I can achieve this?

you can historicize the tag. and use the system.tag.queryTagCalculations function

I think this post will help.