Python keyboard press time and time between two keystrokes

Viewed 734

I want to get the time while the key is pressed and the time between two keystrokes.

For example: W key pressed for x sec.(at the next keypress print that time while the key doesn't pressed).

Example 2:

W pressed for 1 sec.
W released
Time between two keystrokes: 10 sec.
W pressed for 0.5 sec
W released

1 Answers

You can try the perf_counter function from the built-in time module:

from time import perf_counter

# when detected a key press
start = perf_counter()

# when detected the press ended:
end = perf_counter()
print(f'Key pressed for {end-start} seconds.')

Into your code:

import time
import keyboard

while True:
    start = time.perf_counter()
    a = keyboard.read_event()
    if a.name == "esc":
        break
    elif a.event_type == "down":
        b = keyboard.read_event()
        if a.name == "left" or a.name == "right":
            while not b.event_type == "up" and b.name == a.name:
                b = keyboard.read_event()
            end = time.perf_counter()
            print('You pressed', a.name, 'for', end-start, 'seconds.')
Related