get system boot time in seconds in python

You can get the system boot time in seconds using the psutil library in Python. With psutil, we can fetch system information including uptime, which can be used to calculate the system boot time.

Here is an example code that prints the system boot time in seconds:

main.py
import psutil
import datetime

boot_time_timestamp = psutil.boot_time()
bt = datetime.datetime.fromtimestamp(boot_time_timestamp)
delta = datetime.datetime.now() - bt
print(f"System booted since {delta.total_seconds():.0f} seconds.")
234 chars
8 lines

The psutil.boot_time() function returns the system boot time in timestamp format. We then convert this timestamp to a datetime object using datetime.datetime.fromtimestamp(). Finally, we subtract the boot time from the current time to get the timedelta object which we print as the total number of seconds.

gistlibby LogSnag