有 3 个“时间”协议服务,每个服务在不同的端口上运行:
| Service |
Port |
Protocol |
Reference |
| Daytime service |
13 |
TCP and UDP |
[1] |
| Time service |
37 |
TCP and UDP |
[2] |
| Network Time Protocol (NTP) |
123 |
UDP |
[3] |
1.使用“白天”服务(端口 13)
time.nist.gov 上的日间 UDP 服务(端口 13)似乎被禁用或防火墙阻止了 UDP 数据包响应。
但是,您可以调用 DAYTIME TCP 服务来获取当前时间:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "time.nist.gov"
port = 13
s.connect((host, port))
while True:
data = s.recv(1024)
if data:
print(data.decode())
else:
break
s.close()
输出:
59373 21-06-08 17:03:08 50 0 0 535.1 UTC(NIST) *
2。使用“时间”服务(端口 37)
UDP 端口 37 上的 TIME 服务以二进制格式返回一个 32 位无符号整数。您可以将 1900 年 1 月 1 日的相对时间(以秒为单位)转换为日期时间对象。
port = 37
host = "time.nist.gov"
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
msg = "ask for time"
sock.sendto(msg.encode(), (host , port ))
data, addr = sock.recvfrom(1024)
print("received message: %s" % data)
sock.close()
# convert 32-bit unsigned integer in binary format to an integer
seconds = int.from_bytes(data, byteorder='big')
print(f"seconds={seconds}")
dt = datetime(1900, 1, 1) + timedelta(seconds=seconds)
print("rcv=", dt)
print("now=", datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S'))
输出:
received message: b'\xe4j13'
seconds=3832164659
rcv=2021-06-08 18:21:43
now=2021-06-08 18:21:43
3。使用网络时间协议 (NTP) 服务(端口 123)
NTP响应包有四次定义如下:
- orig = 请求发往服务器时客户端的本地时间
- recv = 请求从客户端到达时服务器的接收时间
- tx = 响应留给客户端时服务器的传输时间
- dest = 客户端收到 NTP 消息的本地时间
NTP 与其他时间协议的不同之处在于,通过这 4 个时间,它能够计算时间偏移(两个时钟之间的时间差)和往返延迟(或延迟)。
import ntplib
client = ntplib.NTPClient()
server = "time.nist.gov"
resp = client.request(server, version=3)
print("offset", resp.offset)
print("delay", resp.delay)
print("orig_time:", datetime.utcfromtimestamp(resp.orig_time).strftime('%Y-%m-%d %H:%M:%S.%f'))
print("recv_time:", datetime.utcfromtimestamp(resp.recv_time).strftime('%Y-%m-%d %H:%M:%S.%f'))
print("tx_time :", datetime.utcfromtimestamp(resp.tx_time).strftime('%Y-%m-%d %H:%M:%S.%f'))
print("dest_time:", datetime.utcfromtimestamp(resp.dest_time).strftime('%Y-%m-%d %H:%M:%S.%f'))
输出:
offset 0.004678010940551758
delay 0.06687116622924805
orig_time: 2021-06-10 19:07:52.410973
recv_time: 2021-06-10 19:07:52.449087
tx_time : 2021-06-10 19:07:52.449089
dest_time: 2021-06-10 19:07:52.477846