一个时间同步脚本

Tips

家里有台电脑不知道为啥一直同步不了网络时间,每隔一段时间就慢个几分钟,于是在网上找了点资料和代码拼凑了一个用于Windows时间同步的python脚本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# -*- coding: utf-8 -*-
"""
@author: 0cch
"""

from socket import *
import struct
import sys
import time
import datetime
from ctypes import Structure, windll, pointer
from ctypes.wintypes import WORD

class SYSTEMTIME(Structure):
_fields_ = [
( 'wYear', WORD ),
( 'wMonth', WORD ),
( 'wDayOfWeek', WORD ),
( 'wDay', WORD ),
( 'wHour', WORD ),
( 'wMinute', WORD ),
( 'wSecond', WORD ),
( 'wMilliseconds', WORD ),
]
SetLocalTime = windll.kernel32.SetLocalTime

NTP_SERVER = "pool.ntp.org"
TIME1970 = 2208988800

clientSocket = socket(AF_INET, SOCK_DGRAM)
clientSocket.settimeout(10)

portNumber = 123
def sntp_client():
data = '\x1b' + 47 * '\0'
clientSocket.sendto( data.encode('utf-8'), ( NTP_SERVER, portNumber ))
data, address = clientSocket.recvfrom(1024)
if data:
print ('Response received from:', address)
t_time = struct.unpack( '!12I', data )[10]
t_time -= TIME1970

dt = datetime.datetime.fromtimestamp( t_time )

dt_tuple = dt.timetuple()
st = SYSTEMTIME()
st.wYear = dt_tuple.tm_year
st.wMonth = dt_tuple.tm_mon
st.wDayOfWeek = ( dt_tuple.tm_wday + 1 ) % 7
st.wDay = dt_tuple.tm_mday
st.wHour = dt_tuple.tm_hour
st.wMinute = dt_tuple.tm_min
st.wSecond = dt_tuple.tm_sec
st.wMilliseconds = 0

ret = SetLocalTime( pointer( st ) )
if ret == 0:
print( 'Setting failed. Try as administrator.' )
else:
print( 'Successfully.' )

clientSocket.close()

if __name__ == '__main__':
sntp_client()

Post Directory

Article directory