Setting the time in Win7

Tim Golden mail at timgolden.me.uk
Tue Aug 23 04:26:38 EDT 2011


On 22/08/2011 20:42, Bob Greschke wrote:
> Several people have been hacking away on this computer we are testing
> on, so I'm not sure what settings -- other than all of them -- have been
> messed with, but popen("time ...") seems to work, but system("time ...")
> does not. I'm going to restore the machine to its original state and see
> what happens.

Hoping that this helps: you can programatically set the system time
from within Python by using the pywin32 modules, or ctypes if you
prefer. The code below works for an already-elevated command prompt
by enabling the SystemTime privilege and (crudely) moving the time
forward by five minutes by way of showing what's happening before
resetting it back.

I've commented out the actual SetSystemTime calls just in case anyone
cuts-and-pastes indjudiciously. Ideally you should disable the
privilege afterwards but I've left that out so as not to clutter
the example.

<code>
import os, sys

import win32api
import win32security
import ntsecuritycon

hToken = win32security.OpenProcessToken (
   win32api.GetCurrentProcess (),
   ntsecuritycon.MAXIMUM_ALLOWED
)
time_privilege = win32security.LookupPrivilegeValue (None, 
win32security.SE_SYSTEMTIME_NAME)
win32security.AdjustTokenPrivileges (
   hToken, 0,
   [(time_privilege, win32security.SE_PRIVILEGE_ENABLED)]
)

current_time = win32api.GetSystemTime ()
print "Current time:", current_time
new_time = list (current_time)
new_time[5] += 5
## print win32api.SetSystemTime (*new_time)
print "Current time:", win32api.GetSystemTime ()
## print win32api.SetSystemTime (*current_time)
print "Current time:", win32api.GetSystemTime ()

</code>

TJG



More information about the Python-list mailing list