Python NTP时间同步

1 篇文章 0 订阅
1 篇文章 0 订阅
# synctime.py
import socket
import ctypes
import time,win32api

class NTP_Packet(ctypes.Structure):
    _fields_=[
        ('Control_Word',ctypes.c_int),
        ('root_delay',ctypes.c_int),
        ('root_dispersion',ctypes.c_int),
        ('reference_identifier',ctypes.c_int),
        ('reference_timestamp',ctypes.c_longlong),
        ('originate_timestamp',ctypes.c_longlong),
        ('receive_timestamp',ctypes.c_longlong),
        ('transmit_timestamp_seconds',ctypes.c_int),
        ('transmit_timestamp_fractions',ctypes.c_int)
    ]


def setSystemTime(time_t):
    tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.gmtime(time_t)
    win32api.SetSystemTime(tm_year, tm_mon, tm_wday, tm_mday, tm_hour, tm_min, tm_sec, 0)

def UpdateSysTime():
    soc = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
    NTP_Send = NTP_Packet()
    NTP_Recv = NTP_Packet()
    NTP_Send.Control_Word = socket.htonl(0x0B000000)
    NTP_Send.root_delay = 0
    NTP_Send.root_dispersion = 0
    NTP_Send.reference_identifier = 0
    NTP_Send.reference_timestamp = 0
    NTP_Send.originate_timestamp = 0
    NTP_Send.receive_timestamp = 0
    NTP_Send.transmit_timestamp_seconds = 0
    NTP_Send.transmit_timestamp_fractions = 0
    #把结构体发送出去
    byts= ctypes.string_at(ctypes.addressof(NTP_Send),ctypes.sizeof(NTP_Send))
    soc.sendto(byts,('cn.ntp.org.cn',123))#edu.ntp.org.cn
    data ,addr =soc.recvfrom(2048)
    #将二进制数据拷贝到结构体
    ctypes.memmove(ctypes.addressof(NTP_Recv),data,ctypes.sizeof(NTP_Recv))
    #计算服务器的时间
    TIME_1970 = 2208988800
    ntp_time = socket.ntohl(NTP_Recv.transmit_timestamp_seconds) - TIME_1970
    localTime = time.localtime()
    print('Local Time : ' +time.strftime("%Y-%m-%d %H:%M:%S", localTime))
    setSystemTime(ntp_time)
    print('Time Center: ' +time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ntp_time)),ntp_time,NTP_Recv.transmit_timestamp_seconds)
UpdateSysTime()
print('computer Time is updated!!')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值