使用ntp udp链接服务器(例如:ntp2.aliyun.com), 端口为123, 发送48 bytes(第一字节为0x1b, 后面为0), 接收48bytes, 解析即可.
代码如下:
import socket
import struct
import time
ntpEpochOffset = 2208988800 # since 1970.1.1 00:00:00
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print('bind ntp2.aliyun.com: 123 ..') # ntp1..ntp7
sock.connect(('ntp2.aliyun.com', 123))
data = b'\x1b' + bytes(47) # 0b00011011
sock.send(data)
recv = sock.recvfrom(1024)[0]
m, = struct.unpack('!L', recv[40:44]) #只使用了4 bytes
t = time.localtime(m - ntpEpochOffset) # struct_time
print(f'{t.tm_year}-{t.tm_mon:02d}-{t.tm_mday:02d} {t.tm_hour:02d}:{t.tm_min:02d}:{t.tm_sec:02d}')
sock.close()
#=================output:
# 2023-01-08 15:57:41
标签:02d,校正,socket,python,ntp,tm,aliyun,123 From: https://www.cnblogs.com/csMapx/p/17034803.html