Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

ntp client in python

I've written a ntp client in python to query a time server and display the time and the program executes but does not give me any results. I'm using python's 2.7.3 integrated development environment and my OS is Windows 7. Here is the code:

# File: Ntpclient.py
from socket import AF_INET, SOCK_DGRAM
import sys
import socket
import struct, time

# # Set the socket parameters 

host = "pool.ntp.org"
port = 123
buf = 1024
address = (host,port)
msg = 'time'


# 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", data )[10]
t -= TIME1970
print "Time=%s" % time.ctime(t)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use ntplib:

The following should work on both Python 2 and 3:

import ntplib
from time import ctime
c = ntplib.NTPClient()
response = c.request('pool.ntp.org')
print(ctime(response.tx_time))

Output:

Fri Jul 28 01:30:53 2017

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...