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:-
- Usage Tracking Applications
- Backup Applications
- Antivirus Applications
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.
Up 6 minutes
Things to consider while using the above code:
- It is not necessary for the user to use os.popen(). It is just required to invoke the command-line interpreter, and therefore any other methods/functions leading to the same result (subprocess etc) could be used instead of it.
- The -p after the uptime command is to prettify the output, otherwise, the output contains way too much unwanted information.
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.
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:
- gettickcount64() does not work properly if hybrid sleep is enabled as a turn off mechanism on your OS.
- The program will only work on python version >= 3.x, because of the inclusion of f-strings. For using this on python 2, change the f strings to str.format() or % formatting.
- gettickcount64() does include time elapsed during hibernation or sleep.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.