From The Compiler, 5 Years ago, written in Python.
Embed
  1. class SystemTime(ctypes.Structure):
  2.     # typedef struct _SYSTEMTIME {
  3.     #     WORD wYear;
  4.     #     WORD wMonth;
  5.     #     WORD wDayOfWeek;
  6.     #     WORD wDay;
  7.     #     WORD wHour;
  8.     #     WORD wMinute;
  9.     #     WORD wSecond;
  10.     #     WORD wMilliseconds;
  11.     # } SYSTEMTIME, *PSYSTEMTIME;
  12.     _fields_ = [('Year', ctypes.c_uint16), ('Month', ctypes.c_uint16),
  13.                 ('DayOfWeek', ctypes.c_uint16), ('Day', ctypes.c_uint16),
  14.                 ('Hour', ctypes.c_uint16), ('Minute', ctypes.c_uint16),
  15.                 ('Second', ctypes.c_uint16),
  16.                 ('Milliseconds', ctypes.c_uint16)]
  17.  
  18. def settime(dt):
  19.     time = SystemTime()
  20.     time.Year = dt.year
  21.     time.Month = dt.month
  22.     time.DayOfWeek = dt.isoweekday()
  23.     time.Day = dt.day
  24.     time.Hour = dt.hour
  25.     time.Minute = dt.minute
  26.     time.Second = dt.second
  27.     time.Milliseconds = dt.microsecond // 1000
  28.     # BOOL WINAPI SetSystemTime(_In_  const SYSTEMTIME *lpSystemTime);
  29.     ctypes.windll.kernel32.SetSystemTime(ctypes.byref(time))
  30.  
  31. def getntptime(server='pool.ntp.org'):
  32.     # Unix epoch is 1.1.1970, NTP is 1.1.1900
  33.     system_epoch = datetime.date(*time.gmtime(0)[0:3])
  34.     ntp_epoch = datetime.date(1900, 1, 1)
  35.     epoch_diff = (system_epoch - ntp_epoch).days * 24 * 3600
  36.     client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  37.     data = b'\x1b' + (47 * b'\0')
  38.     client.sendto(data, (server, 123))
  39.     data, address = client.recvfrom(1024)
  40.     if data:
  41.         # network (big-endian), 12 * unsigned int, 11th value
  42.         epoch = struct.unpack('!12I', data)[10]
  43.         print(epoch)
  44.         epoch -= epoch_diff
  45.         print(epoch)
  46.         dt = datetime.datetime.utcfromtimestamp(epoch)
  47.         return dt
  48.     return False
  49.  
  50. def main():
  51.     settime(getntptime())