Skip to content

Instantly share code, notes, and snippets.

@apsun
Created October 19, 2015 22:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apsun/09b0e5ff5d1b96a26eaf to your computer and use it in GitHub Desktop.
Save apsun/09b0e5ff5d1b96a26eaf to your computer and use it in GitHub Desktop.
# Requires: ntplib (https://pypi.python.org/pypi/ntplib/)
import ctypes
import time
import ntplib
MAX_RETRIES = 10
RETRY_DELAY = 30
NTP_SERVERS = [
"0.tw.pool.ntp.org",
"0.asia.pool.ntp.org",
"1.asia.pool.ntp.org",
"2.asia.pool.ntp.org",
"3.asia.pool.ntp.org"
]
class SYSTEMTIME(ctypes.Structure):
_fields_ = [("wYear", ctypes.c_ushort),
("wMonth", ctypes.c_ushort),
("wDayOfWeek", ctypes.c_ushort),
("wDay", ctypes.c_ushort),
("wHour", ctypes.c_ushort),
("wMinute", ctypes.c_ushort),
("wSecond", ctypes.c_ushort),
("wMilliseconds", ctypes.c_ushort)]
def get_network_time(server_list):
client = ntplib.NTPClient()
for server_address in server_list:
print("Trying server: " + server_address)
try:
response = client.request(server_address, version=3)
except ntplib.NTPException as ex:
print("Failed: " + ex.args[0])
continue
local_time = time.localtime(response.tx_time)
utc_time = time.gmtime(response.tx_time)
print("Success! Current time: " + time.strftime("%Y-%m-%d %H:%M:%S", local_time))
return utc_time
print("Exhausted all servers.")
return None
def set_system_time(utc_time):
native_struct = SYSTEMTIME(utc_time.tm_year,
utc_time.tm_mon,
utc_time.tm_wday,
utc_time.tm_mday,
utc_time.tm_hour,
utc_time.tm_min,
utc_time.tm_sec)
success = ctypes.windll.kernel32.SetSystemTime(ctypes.byref(native_struct))
assert success != 0
def main():
for i in range(MAX_RETRIES):
utc_time = get_network_time(NTP_SERVERS)
if utc_time is not None:
set_system_time(utc_time)
return
time.sleep(RETRY_DELAY)
print("Reached max retry count! Please try again later.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment