get started time of a process using psutil in poython
- User
get started time of a process using psutil in poython
- Assistant
To get the start time of a process using
psutilin Python, you can utilize thecreate_time()method of aProcessobject. This method returns the time the process was spawned as a UNIX timestamp. To convert this timestamp into a human-readable format, you can use thedatetimemodule.Here's how you can achieve this:
-
First, ensure you have
psutilinstalled in your environment. If not, you can install it using pip:pip install psutil -
Use the following code snippet as a guide to fetch the start time of a process by its PID (Process ID). You need to replace
YOUR_PROCESS_PIDwith the actual Process ID you are interested in:import psutil from datetime import datetime # Replace YOUR_PROCESS_PID with the actual process ID pid = YOUR_PROCESS_PID try: # Create a Process object p = psutil.Process(pid) # Fetch the start time of the process start_time = p.create_time() # Convert the UNIX timestamp to a datetime object start_time_readable = datetime.fromtimestamp(start_time).strftime("%Y-%m-%d %H:%M:%S") print(f"Process {pid} started at: {start_time_readable}") except psutil.NoSuchProcess: print(f"No process found with PID {pid}")
-