前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python windows系统时间同步

python windows系统时间同步

作者头像
py3study
发布2020-01-07 16:37:59
3K0
发布2020-01-07 16:37:59
举报
文章被收录于专栏:python3
代码语言:javascript
复制
#!/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')
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档