get system boot time in minutes in python

Here's a code snippet for getting the system boot time in minutes using Python's datetime module.

main.py
import datetime

def get_boot_time():
    with open('/proc/stat', 'r') as f:
        for line in f:
            if line.startswith('btime'):
                boot_time = float(line.split()[1])
                return datetime.datetime.fromtimestamp(boot_time).strftime('%Y-%m-%d %H:%M:%S')

def get_uptime():
    with open('/proc/uptime', 'r') as f:
        uptime_seconds = float(f.readline().split()[0])
        return int(uptime_seconds // 60)

boot_time_str = get_boot_time()
boot_time = datetime.datetime.strptime(boot_time_str, '%Y-%m-%d %H:%M:%S')
now = datetime.datetime.now()
uptime_minutes = get_uptime()

minutes_since_boot = (now - boot_time).total_seconds() // 60
print("System boot time: {}".format(boot_time_str))
print("Minutes since boot: {}".format(minutes_since_boot))
print("Uptime in minutes: {}".format(uptime_minutes))
840 chars
24 lines

This script first opens the /proc/stat file and searches for the "btime" line, which contains the system boot time in seconds since epoch. It then converts that to a datetime object using datetime.datetime.fromtimestamp().

The script then calculates the minutes since the last boot by subtracting the boot time from the current time and dividing the result by 60. Finally, it uses the /proc/uptime file to get the system uptime in seconds and converts it to minutes.

gistlibby LogSnag