0

I needed a python script for detecting idle time in seconds. This script would run for every 15 minutes in Task scheduler as long as the system is logged on. I found the below mentioned script to be very useful. detecting idle time using python.

from ctypes import Structure, windll, c_uint, sizeof, byref
class LASTINPUTINFO(Structure):
_fields_ = [
    ('cbSize', c_uint),
    ('dwTime', c_uint),
]

def get_idle_duration():
lastInputInfo = LASTINPUTINFO()
lastInputInfo.cbSize = sizeof(lastInputInfo)
windll.user32.GetLastInputInfo(byref(lastInputInfo))
millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
return round((millis / (1000.0*60.0))%60, 2)

The issue is, when the the computer is not switched off for more than a month, this script gives incorrect output. Such as, it shows that the idle time is nearly 10mins instead of showing the actual time for every 1 hour even at midnight when there is no one using the system.

Once I have restarted the system, the script works fine. It shows the correct output for some days. But when the system is again running continuously for many days, it shows less time instead of the right amount of time.

For Example: If the user has let the system at 8pm without switching it off. Then at midnight, the value must be something as 4*60 minutes but instead it shows less than 10 minutes.

  • and what is your question? – Alex Jun 19 '23 at 08:12
  • If the user has let the system at 8pm without switching it off. Then at midnight, the value must be something as 4*60 minutes but instead it shows less than 10 minutes. Why does it show incorrect value when system is continuously running without any user interactions? Does it have something to do with the system being run without switching it off? Some kind of system memory related problem or some other system issues? – Nambirajan M Jun 19 '23 at 08:15
  • please edit your question and show your code. We can not guess why something is happening. – Alex Jun 19 '23 at 08:18
  • 1
    From the MS docs on GetTickCount(): "Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days." In general, when you have a roll-over, you need to be very careful with the arithmetics. I have not enough experience with the Windows API to suggest what you need to fix exactly, though. – Hans-Martin Mosner Jun 19 '23 at 08:42

0 Answers0