This is a simple script to 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:
For example, you may get local datetime when process 12345 started:
import datetime import btime datetime.datetime.fromtimestamp(btime.process_time(12456)[1])
View the source code in github gists:
This file contains 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
''' | |
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 |
Comments