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 reboots or shutdowns a pi depending on how long I hold the button. My first python script for some years but it works as intended.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/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.