Welcome, guest | Sign In | My Account | Store | Cart

This recipe will help getting windows uptime using the "net statistics server" info.

Python, 28 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def uptime():
    """Returns a datetime.timedelta instance representing the uptime in a Windows 2000/NT/XP machine"""
    import os, sys
    import subprocess
    if not sys.platform.startswith('win'):
        raise RuntimeError, "This function is to be used in windows only"
    cmd = "net statistics server"
    p = subprocess.Popen(cmd, shell=True, 
          stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    (child_stdin, child_stdout) = (p.stdin, p.stdout)
    lines = child_stdout.readlines()
    child_stdin.close()
    child_stdout.close()
    lines = [line.strip() for line in lines if line.strip()]
    date, time, ampm = lines[1].split()[2:5]
    #print date, time, ampm
    m, d, y = [int(v) for v in date.split('/')]
    H, M = [int(v) for v in time.split(':')]
    if ampm.lower() == 'pm':
        H += 12
    import datetime
    now = datetime.datetime.now()
    then = datetime.datetime(y, m, d, H, M)
    diff = now - then
    return diff

if __name__ == '__main__':
    print uptime()

I don't know a simple way of getting the machine uptime with python standard modules, so I've found it is possible to find out uptime with the windows "net" command.

We open a subprocess with shell=True and run the appropriate "net statistics server" command. The output is read from the process stdout.

The second non blank line in the output will look like this:

Statistics since

So we just parse it and return a timedeltam which is the difference from datetime.datetime.now() to the time reported in that line.

-- João Paulo Farias

2 comments

Kevan Heydon 17 years, 10 months ago  # | flag

Use win32pdh. You can use the win32pdh module like this:

import win32pdh

path = win32pdh.MakeCounterPath( ( None, 'System', None, None, 0, 'System Up Time') )

query = win32pdh.OpenQuery()

handle = win32pdh.AddCounter( query, path )

win32pdh.CollectQueryData( query )

seconds = win32pdh.GetFormattedCounterValue( handle, win32pdh.PDH_FMT_LONG | win32pdh.PDH_FMT_NOSCALE )[ 1 ]

print "uptime: %d seconds" %( seconds )
Filip Dehond 17 years, 9 months ago  # | flag

for a simple way just use uptime.exe from M$

print os.popen(uptime.exe).readline()