Skip to content

Instantly share code, notes, and snippets.

@socrateslee
Created May 30, 2013 04:21
Show Gist options
  • Save socrateslee/5675695 to your computer and use it in GitHub Desktop.
Save socrateslee/5675695 to your computer and use it in GitHub Desktop.
Get the Linux birth time of the system or a process using /proc/stat and /proc/pid/stat. For example, you may get local datetime when process 12345 started: import datetime import btime datetime.datetime.fromtimestamp(btime.process_time(12456)[1])
'''
Get the Linux birth time of the system or a process using /proc/stat
and /proc/pid/stat.
For example, you may get local datetime when process 12345 started:
import datetime
import btime
datetime.datetime.fromtimestamp(btime.process_time(12456)[1])
'''
import os
def system_btime():
'''
Get the timestamp when system is booted.
'''
stat = open('/proc/stat').readlines()
btime_line = [i.strip() for i in stat if i.startswith('btime')]
return int(btime_line[0].split(' ')[1])
def process_btime(pid):
'''
Return a tuple (secs, timestamp) of a process.
secs is the seconds when process started after system booted,
timestamp is the seconds.
'''
stat = open('/proc/%s/stat' % pid).read()
clock = int(stat.split(' ')[21])
secs = clock / os.sysconf('SC_CLK_TCK')
timestamp = system_btime() + secs
return secs, timestamp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment