Skip to content

Instantly share code, notes, and snippets.

@abhijitmamarde
Last active February 23, 2021 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhijitmamarde/d5ea23976e4d1a318be0f92f07f955a1 to your computer and use it in GitHub Desktop.
Save abhijitmamarde/d5ea23976e4d1a318be0f92f07f955a1 to your computer and use it in GitHub Desktop.
get correct unix timestamp from ntp server
"""
Original source:
https://www.mattcrampton.com/blog/query_an_ntp_server_from_python/
"""
from socket import AF_INET, SOCK_DGRAM
import socket
import struct
def get_unixtime(host="in.pool.ntp.org"):
port = 123
buf = 1024
address = (host, port)
msg = '\x1b' + 47 * '\0'
# reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800 # 1970-01-01 00:00:00
# connect to server
client = socket.socket(AF_INET, SOCK_DGRAM)
client.sendto(msg.encode('utf-8'), address)
msg, address = client.recvfrom(buf)
t = struct.unpack("!12I", msg)[10]
t -= TIME1970
return t
def test_get_unixtime():
import datetime as dt
ntptime = get_unixtime()
localtime = dt.datetime.timestamp(dt.datetime.now())
print(ntptime, localtime, localtime-ntptime)
if __name__ == "__main__":
test_get_unixtime()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment