Skip to content

Instantly share code, notes, and snippets.

@stevemk14ebr
Created October 8, 2018 15:19
Show Gist options
  • Save stevemk14ebr/5be1a68d14ae84192d70e9732d9856f7 to your computer and use it in GitHub Desktop.
Save stevemk14ebr/5be1a68d14ae84192d70e9732d9856f7 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from socket import AF_INET, SOCK_DGRAM
from datetime import datetime
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 datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S')
if __name__ == "__main__":
print getNTPTime()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment