I could not find code that I liked for timing how long we hold a button attached to a pi. I rolled my own. Probably not the fastest, or most elegant, but hopefully simple and useful.
I use this for a single button that will reboot or shutdown a pi depending on how long I hold the button. My first python script for some years but it works as intended.
#!/usr/bin/env python3
# python3 script to reboot or shutdown from one button press of varying hold time
from gpiozero import Button
from time import time
from os import system
GPIOnumber = 21
secondsdifference = 0
rebootseconds = 3
poweroffseconds = 5
mybutton = Button(GPIOnumber)
def get_int_time():
return int(time())
def shutdown():
system("sudo poweroff")
def reboot():
system("sudo reboot")
while True:
mybutton.wait_for_press()
starttime = get_int_time()
mybutton.wait_for_release()
timenow = get_int_time()
secondsdifference = timenow - starttime
if ( secondsdifference > poweroffseconds):
shutdown()
elif ( secondsdifference > rebootseconds):
reboot()
starttime = 0
I run this as a root crontab job at reboot.