Search code examples
pythonwindowspsutil

Using psutil to determine duration of applications on Windows


I'm using Windows and I want to write a program in Python that returns the length of time that has elapsed since an application began. I'm using psutil to do so and this is my initial approach:

psutil.process_iter.cache_clear()
processes = psutil.process_iter()
for process in processes:
        duration = time.time() - process.create_time() 
        converted_time = convert_seconds(duration) # Converts seconds into a more readable form
        print(converted_time)

Since there can be multiple processes running for a single application, will there always be a process running whose duration is the same as the duration of the application since it first started? For example, if I've had Google Chrome open for X hours, will there always be a process whose duration is also X hours?

So, as long as I know the longest running process for a certain application, that's essentially how long the application has been open for, right? Is there a better approach to doing this?


Solution

    1. Yes, there's always a process that have the same duration than the duration of the application, it's the main process. For example, for Chrome it's chrome.exe.
    2. No, the longest running process for an application doesn't always have the same duration as the application. For example there's applications that start background process that don't end when the application stops.

    A better way for doing that will probably to find the main process of the application, that is in most cases the executable of the application, (chrome.exe for Chrome, msedge.exe for Edge, explorer.exe for the File Explorer, ...) and return it's duration time.