python中的ntp客户端
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12664295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ntp client in python
提问by Howard Hugh
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:
我用python编写了一个ntp客户端来查询时间服务器并显示时间,程序执行但没有给我任何结果。我使用的是python的2.7.3集成开发环境,我的操作系统是Windows 7。代码如下:
# 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 "\tTime=%s" % time.ctime(t)
回答by Chengy
It should be
它应该是
msg = '\x1b' + 47 * 'msg = 'time'
'
Instead of
代替
import ntplib
from time import ctime
c = ntplib.NTPClient()
response = c.request('pool.ntp.org')
print(ctime(response.tx_time))
But as Maksym said you should use ntplib instead.
但正如 Maksym 所说,您应该改用 ntplib。
回答by Maksym Polshcha
回答by Anuj Gupta
Use ntplib:
使用ntplib:
The following should work on both Python 2 and 3:
以下应该适用于 Python 2 和 3:
Fri Jul 28 01:30:53 2017
Output:
输出:
msg = '\x1b' + 47 * '#!/usr/bin/env python
from contextlib import closing
from socket import socket, AF_INET, SOCK_DGRAM
import struct
import time
NTP_PACKET_FORMAT = "!12I"
NTP_DELTA = 2208988800 # 1970-01-01 00:00:00
NTP_QUERY = b'\x1b' + 47 * b'##代码##'
def ntp_time(host="pool.ntp.org", port=123):
with closing(socket( AF_INET, SOCK_DGRAM)) as s:
s.sendto(NTP_QUERY, (host, port))
msg, address = s.recvfrom(1024)
unpacked = struct.unpack(NTP_PACKET_FORMAT,
msg[0:struct.calcsize(NTP_PACKET_FORMAT)])
return unpacked[10] + float(unpacked[11]) / 2**32 - NTP_DELTA
if __name__ == "__main__":
print time.ctime(ntp_time()).replace(" ", " ")
'
.......
t = struct.unpack( "!12I", msg )[10]
回答by user3696940
回答by Michael
Here is a fix for the above solution, which adds fractions of seconds to the implementation and closes the socket properly. As it's actually just a handful lines of code, I didn't want to add another dependency to my project, though ntplibadmittedly is probably the way to go in most cases.
这是对上述解决方案的修复,它为实现增加了几分之一秒并正确关闭套接字。由于它实际上只是几行代码,我不想在我的项目中添加另一个依赖项,尽管ntplib在大多数情况下这可能是可行的方法。

