Reputation: 95
I want to find mouse click and key press is occur or not between start time and end time (starttime:9:30 and endtime:10:30) using Python script.
Python code is here:
from pynput.mouse import Listener
from pynput.keyboard import Key, Listener
def on_click(x, y, button, pressed):
if pressed:
print("Mouse clicked.")
def on_press(key):
print("key is pressed")
with Listener(on_click=on_click,on_press=on_press) as listener:
listener.join()
with this I am able to get the mouse click and key press, but I don't have idea for time-interval.
Upvotes: 2
Views: 6700
Reputation: 106
First of all your code didn't work for me. I had to make some changes in order to test it. The problem in my case were the events mouse and keyboard at the same time.
Here I post my changed code:
from pynput.keyboard import Key, Listener
from pynput.mouse import Listener
def on_click(x, y, button, pressed):
if pressed:
print("Mouse clicked.")
def on_press(key):
print("key is pressed")
from pynput import keyboard
key_listener = keyboard.Listener(on_press=on_press)
key_listener.start()
with Listener(on_click=on_click) as listener:
listener.join()
(Source: Using Mouse and Keyboard Listeners Together in Python)
If you want to count seconds, minutes and so on, you can use time like @Ujjwal Dash said.
The Mouse events will be noticed if its between 1 and 10 seconds since the script was started.
import time
from pynput.keyboard import Key, Listener
from pynput.mouse import Listener
def on_click(x, y, button, pressed):
delta_time = (int(time.time()-start_time))
if delta_time >=1 and delta_time <=10:
if pressed:
print("Mouse clicked.")
def on_press(key):
delta_time = (int(time.time()-start_time))
print(delta_time)
print("key is pressed")
start_time = time.time()
from pynput import keyboard
key_listener = keyboard.Listener(on_press=on_press)
key_listener.start()
with Listener(on_click=on_click) as listener:
listener.join()
delta_time ... time in seconds since script start
If you want it to listen to a specific time of the day, you can work with the unix time and convert it with the time module. In this code the mouse will be noticed if it's between 7:00 and 10:00 localtime hours.
import time
from pynput.keyboard import Key, Listener
from pynput.mouse import Listener
def check_time():
t = time.localtime(time.time())
if t.tm_hour<= 10 and t.tm_hour>=7:
return True
else:
return False
def on_click(x, y, button, pressed):
if check_time():
if pressed:
print("Mouse clicked.")
else:
pass
def on_press(key):
print("key is pressed")
from pynput import keyboard
key_listener = keyboard.Listener(on_press=on_press)
key_listener.start()
with Listener(on_click=on_click) as listener:
listener.join()
Upvotes: 3
Reputation: 823
I don't know much about it, but I think you could do use the function time
from the module time
. You can bind start = time.time()
to your start button and end = time.time()
to your end button. Then, for each interval use i = end - start
.
Upvotes: 0