python使用ntp动态校正时间

使用ntp udp链接服务器(例如:ntp2.aliyun.com), 端口为123, 发送48 bytes(第一字节为0x1b, 后面为0), 接收48bytes, 解析即可.

代码如下:

import socket
import struct
import time

import os

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}')

i = os.system(f'date {t.tm_year}-{t.tm_mon:02d}-{t.tm_mday:02d} && time {t.tm_hour:02d}:{t.tm_min:02d}:{t.tm_sec:02d}')
print("NTP SERVER校正时间成功:", i)

sock.close()

#=================output:
# 2023-01-08 15:57:41

 

posted @ 2023-01-08 16:01  沧海小小粟  阅读(462)  评论(0编辑  收藏  举报