19

我在 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)
4

5 回答 5

25

使用ntplib

以下应该适用于 Python 2 和 3:

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

输出:

Fri Jul 28 01:30:53 2017
于 2012-09-30T20:13:47.577 回答
20

这是对上述解决方案的修复,它为实现增加了几分之一秒并正确关闭了套接字。因为它实际上只是几行代码,我不想在我的项目中添加另一个依赖项,尽管ntplib在大多数情况下可能是要走的路。

#!/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'\0'  

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("  ", " ")
于 2015-10-30T12:31:37.753 回答
4

它应该是

msg = '\x1b' + 47 * '\0' 

代替

msg = 'time'

但正如 Maksym 所说,您应该改用 ntplib。

于 2012-09-30T20:03:59.790 回答
0

对不起,如果我的回答不能满足您的期望。我认为使用现有的解决方案是有意义的。ntplib是一个非常好的与 NTP 服务器一起工作的库。

于 2012-09-30T20:06:47.340 回答
0
msg = '\x1b' + 47 * '\0'
.......
t = struct.unpack( "!12I", msg )[10]
于 2014-06-01T14:49:22.120 回答