0

As per Python module to change system date and time - We are able to change the system time using this code. I have adapted this code and changed it accordingly, but executing the script changes the time to the UTC format, but updates to the correct time about 10 seconds later. This unexplained behaviour has prompted me to instead, use the SetLocalTime method instead. However, I cannot get this to work.

import socket
import struct
import sys
import time
import win32api

TIME1970 = 2208988800

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = '\x1b' + 47 * '\0'
client.sendto(data.encode(), ('10.0.0.1', 123))
data, address = client.recvfrom(1024)
if data:
    print('Response received from:', address)
    t = struct.unpack('!12I', data)[10]
    t -= TIME1970
    tf = time.strptime(time.ctime(t))

time_tuple = (tf[0], # Year
            tf[1], # Month
            tf[6], # Day of Week
            tf[2], # Day
            tf[3], # Hour
            tf[4], # Minute
            tf[5], # Second
            0,#int(round(tf[5] * 1000)), # Millisecond
    )
print(tf)
win32api.SetLocalTime(*time_tuple)

I am returned with the error TypeError: SetLocalTime() takes exactly 1 argument (8 given). I am aware the SetLocalTime function takes the exact same parameters as SetSystemTime, but it's not.

I cannot find anywhere on Google with any examples so I'm unable to complete my code.

Any suggestions are greatly appreciated. Thank you.

juiceb0xk
  • 949
  • 3
  • 19
  • 46
  • @eryksun Thanks, it works! I didn't specifically know it required a datetime.datetime instance. I was trying to use pywin32.time methods and methods from the time module itself, not datetime. – juiceb0xk Jan 04 '18 at 13:55

1 Answers1

1

The win32api module wraps SetSystemTime to take the SYSTEMTIME structure fields as 8 separate function parameters. The time should be passed as UTC. wDayOfWeek is ignored (i.e. pass it as 0).

The win32api module wraps SetLocalTime more conveniently and idiomatically. It takes a datetime.datetime instance instead of requiring separate parameters. For example:

import datetime
import win32api

dt = datetime.datetime(2018, 1, 4, 14, 30)
win32api.SetLocalTime(dt)

The Token of the calling process must have SeSystemtimePrivilege, so generally the user needs to be an elevated administrator.

Eryk Sun
  • 33,190
  • 5
  • 92
  • 111