Open In App

Getting the time since OS startup using Python

Uptime is the time elapsed since the Operating system started. Operating systems have discrete mechanisms to keep track of this time, which they further utilize for performing OS related tasks. This time is particularly useful for certain applications such as:-

 In this article, we will take a look at methods of getting the time since OS startup of different operating systems. 



Getting Uptime on MAC OS and Linux

For Mac OS and Linux users, the method is very trivial. There exists an inbuilt command offered by the terminal of the OS, which allows for the extraction of the uptime. We would be integrating that command-line method into our Python program.






# for using os.popen()
import os
 
# sending the uptime command as an argument to popen()
# and saving the returned result (after truncating the trailing \n)
t = os.popen('uptime -p').read()[:-1]
 
print(t)

Output 

 Up 6 minutes

Things to consider while using the above code:

GETTING UPTIME ON WINDOWS OS

For Windows, we would be using an inbuilt API function found in Windows OS under the name gettickcount64(). This function retrieves the number of milliseconds that have elapsed since the system was started. 




# ctypes required for using GetTickCount64()
import ctypes
 
# getting the library in which GetTickCount64() resides
lib = ctypes.windll.kernel32
 
# calling the function and storing the return value
t = lib.GetTickCount64()
 
# since the time is in milliseconds i.e. 1000 * seconds
# therefore truncating the value
t = int(str(t)[:-3])
 
# extracting hours, minutes, seconds & days from t
# variable (which stores total time in seconds)
mins, sec = divmod(t, 60)
hour, mins = divmod(mins, 60)
days, hour = divmod(hour, 24)
 
# formatting the time in readable form
# (format = x days, HH:MM:SS)
print(f"{days} days, {hour:02}:{mins:02}:{sec:02}")

 

 

Output

 

 0 days, 3:09:04

 

The above output states, that this system is running for 3 hours, 9 minutes, and 4 seconds (0 days). If the system would be used for more than one day (or hours = 24+) then the hours will roll back to 0, and the days will be incremented. 

 

Things to consider while running the above code:

 

 


Article Tags :