Python 官方文档:入门教程 => 点击学习
#!/usr/bin/env python # coding: utf8 # Usage: 指定ntpserver域名到ntpserver_domains变量即可 import Socket import struct import ti
#!/usr/bin/env python
# coding: utf8
# Usage: 指定ntpserver域名到ntpserver_domains变量即可
import Socket
import struct
import time
import win32api
import subprocess
import os
import sys
def gettime(ntpserver_ips):
TIME_1970 = 2208988800L
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.settimeout(3)
data = '\x1b' + 47 * '\0'
Port=123
for server in ntpserver_ips:
success = False
count = 1
'''每个ip尝试3次'''
while not success and count < 4:
try:
client.sendto(data, (server, Port))
data = client.recvfrom(1024)[0]
success = True
print server+' get time success, tried '+str(count)+' times.'
except socket.timeout:
print server+' get time failed, tried '+str(count)+' times.'
count += 1
if success == True:
break
data_result = struct.unpack('!12I', data)[10]
data_result -= TIME_1970
return data_result
def settime(nowtime):
tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.gmtime(nowtime)
win32api.SetSystemTime(tm_year, tm_mon, tm_wday, tm_mday, tm_hour, tm_min, tm_sec, 0)
print u'Set system time success.'
def getip_with_domains(ntpserver_domains):
ips = []
for i in ntpserver_domains:
ip = socket.gethostbyname_ex(i)[2]
ips.extend(ip)
return ips
if __name__ == '__main__':
ntpserver_domains = ['cn.pool.ntp.org', 'ntp.sjtu.edu.cn', 'time.windows.com']
ntpserver_ips = getip_with_domains(ntpserver_domains)
if not ntpserver_ips or len(ntpserver_ips) != len(set(ntpserver_ips)):
print u'Some domain can not resolve ip.'
print os.system('pause')
sys.exit()
else:
nowtime = gettime(ntpserver_ips)
settime(nowtime)
print u'Now Time:',time.strftime('%Y-%m-%d %X')
os.system('pause')
--结束END--
本文标题: python windows系统时间同步
本文链接: https://lsjlt.com/news/190089.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0