Skip to content

Instantly share code, notes, and snippets.

@monperrus
Created March 16, 2025 10:06
Show Gist options
  • Select an option

  • Save monperrus/29de44da9fe858015980d2cbe852e4b1 to your computer and use it in GitHub Desktop.

Select an option

Save monperrus/29de44da9fe858015980d2cbe852e4b1 to your computer and use it in GitHub Desktop.
get age of process in python
#!/usr/bin/python3
# get process age in second
import psutil
import time
import sys
import datetime
def get_process_age(pid):
try:
# Get the process object
process = psutil.Process(pid)
# Get the creation time of the process
creation_time = process.create_time()
# Get the current time
current_time = time.time()
# Calculate the age of the process in seconds
age_in_seconds = current_time - creation_time
# Convert age to a more readable format (e.g., seconds, minutes, hours)
age = str(datetime.timedelta(seconds=age_in_seconds))
return age
except psutil.NoSuchProcess:
return None # Process does not exist
except Exception as e:
return str(e) # Handle other exceptions
# # Example usage
# pid = 1234 # Replace with the actual PID of the process you want to check
# age = get_process_age(pid)
# if main
if __name__ == "__main__":
pid = sys.argv[1]
age = get_process_age(int(pid))
if age is not None:
print(f"Process with PID {pid} is {age} seconds old.")
else:
print(f"Process with PID {pid} does not exist.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment