Query an NTP server from Python

I came across a need to query an NTP server to get the current time from a python script. There are some great python modules you can install which will take care of the heavy lifting (one great one is ntplib), but I wanted to be able to do these NTP queries without requiring the host to install 3rd party python packages.

As it turns out, it wasn't too difficult after checking out a few stack overflow threads, I put together this little script...

#!/usr/bin/env python
from socket import AF_INET, SOCK_DGRAM
import sys
import socket
import struct, time

def getNTPTime(host = "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 = 2208988800L # 1970-01-01 00:00:00

        # connect to server
        client = socket.socket( AF_INET, SOCK_DGRAM)
        client.sendto(msg, address)
        msg, address = client.recvfrom( buf )

        t = struct.unpack( "!12I", msg )[10]
        t -= TIME1970
        return time.ctime(t).replace("  "," ")

if __name__ == "__main__":
        print getNTPTime()

Create a file, paste that code in, chmod +x it and fire it off.

Post A Twitter Response To This Blog Post

To: @mattccrampton