Created
March 16, 2025 10:06
-
-
Save monperrus/29de44da9fe858015980d2cbe852e4b1 to your computer and use it in GitHub Desktop.
get age of process in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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