Skip to content

Instantly share code, notes, and snippets.

@tranch
Created November 28, 2018 09:20
Show Gist options
  • Save tranch/4855b1bc90283859b8668bb67031d312 to your computer and use it in GitHub Desktop.
Save tranch/4855b1bc90283859b8668bb67031d312 to your computer and use it in GitHub Desktop.
import socket
import struct
import time
# datetime.date(1970, 1, 1) - datetime.date(1900, 1, 1)
NTP_DELTA = 2208988800
NTP_SERVER = '0.cn.pool.ntp.org'
def get_ntp_time():
data = bytearray(48)
data[0] = 0x1B
val = 0
addr = socket.getaddrinfo(NTP_SERVER, 123)[0][-1]
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
n = sock.sendto(data, addr)
data, addr = sock.recvfrom(2048)
val = struct.unpack("!12I", data)[10]
return val - NTP_DELTA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment