python windows時間同步工具


由於某種原因(BIOS電池沒電),電腦的系統時間會與我們的北京時間不同步,將會導致如下問題:

1. 搶火車票的時候已經過時間了

2.別的同事都走了,你還以為沒下班

……

 

規避問題的方法:同步系統時間

一. 獲取時間

在這里,我們有兩種方法

1.  通過系統請求網站服務器頭部返回Respones Headers

獲取Date 參數值,修改系統時間

復制代碼
    def getTime(self,url):
        conn = http.client.HTTPConnection(url)
        conn.request("GET", "/")
        r = conn.getresponse()
        # r.getheaders() #獲取所有的http頭
        ts = r.getheader('date')  # 獲取http頭date部分
        # 將GMT時間轉換成北京時間
        ltime = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S")  # 格式ts
        ttime = time.localtime(time.mktime(ltime) + 8 * 60 * 60)  # +東八區
        dat = "date %u-%02u-%02u" % (ttime.tm_year, ttime.tm_mon, ttime.tm_mday)
        tm = "time %02u:%02u:%02u" % (ttime.tm_hour, ttime.tm_min, ttime.tm_sec)
        return [dat, tm]
復制代碼

 

在這里解釋下strptime函數中,時間字符串的格式化說明

%y 兩位數的年份表示(00-99)
%Y 四位數的年份表示(000-9999)
%m 月份(01-12)
%d 月內中的一天(0-31)
%H 24小時制小時數(0-23)
%I 12小時制小時數(01-12) 
%M 分鍾數(00=59)
%S 秒(00-59)

%a 本地簡化星期名稱
%A 本地完整星期名稱
%b 本地簡化的月份名稱
%B 本地完整的月份名稱
%c 本地相應的日期表示和時間表示
%j 年內的一天(001-366)
%p 本地A.M.或P.M.的等價符
%U 一年中的星期數(00-53)星期天為星期的開始
%w 星期(0-6),星期天為星期的開始
%W 一年中的星期數(00-53)星期一為星期的開始
%x 本地相應的日期表示
%X 本地相應的時間表示
%Z 當前時區的名稱
%% %號本身n

代碼中的%參數解析

%[flags][width][.precision][size]type

%02u : 
“0”是flags,表示補“0”;
“2”是width,表示輸出的長度;
“u”是type, 表示數據的類型為無符號數;
整個意思是:打印一個無符號數的兩位(十進制),若不滿兩位則在前面補0.

 

2. 通過獲取授時中心的標准時間修改系統時間

授時中心的網址:

http://www.pool.ntp.org/
ntplib 下載地址:
https://pypi.python.org/pypi/ntplib/

復制代碼
    def getTime(self):
        c = ntplib.NTPClient()
        response = c.request('pool.ntp.org')  # 授時中心的網址
        ts_stamp = response.tx_time
        ts = time.localtime(ts_stamp)
        ttime = time.localtime(time.mktime(ts) + 8 * 60 * 60)  # +東八區
        return ts
復制代碼

 

二. 同步時間

獲取時間后,我們要同步時間,同步時間也有兩種方法

1.通過os.system 同步

    def setTime(self,time):
        os.system(time[0])
        os.system(time[1])

2.通過win32api.SetSystimeTime 同步

    def setTime(self,time_cls):
        ttime = time.localtime(time.mktime(time_cls) - 8 * 60 * 60)  # 本為東八區,卻set后多出8小時 UTC多了8個小時 , 所以……
        time_cls = ttime
        win32api.SetSystemTime(time_cls.tm_year, time_cls.tm_mon, time_cls.tm_wday, time_cls.tm_mday, time_cls.tm_hour, time_cls.tm_min, time_cls.tm_sec, 0)

 

完整代碼如下:

復制代碼
# -*- coding:utf-8 -*-
# 1.獲取網絡時間
# 2.修改系統時間
import http.client
import time
import os,sys
import ntplib
import win32api

'''
'同步時間類
'''
class syctimes():
    def __init__(self):
        if sys.argv.__len__() == 1:
            try:
                time_list = self.getTime1()
                self.setTime1(time_list)
            except:
                time_list = self.getTime2('www.baidu.com')
                self.setTime2(time_list)
        for arg in sys.argv:
            if arg == '-1':
                time_list = self.getTime1()
                self.setTime1(time_list)
            if arg == '-2':
                time_list = self.getTime2('www.baidu.com')
                self.setTime2(time_list)

        sys.exit()

    def getTime1(self):
        c = ntplib.NTPClient()
        response = c.request('pool.ntp.org')  # 授時中心的網址
        ts_stamp = response.tx_time
        ts = time.localtime(ts_stamp)
        ttime = time.localtime(time.mktime(ts) + 8 * 60 * 60)  # +東八區
        return ts

    def getTime2(self,url):
        conn = http.client.HTTPConnection(url)
        conn.request("GET", "/")
        r = conn.getresponse()
        # r.getheaders() #獲取所有的http頭
        ts = r.getheader('date')  # 獲取http頭date部分
        # 將GMT時間轉換成北京時間
        ltime = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S")  # 格式ts
        ttime = time.localtime(time.mktime(ltime) + 8 * 60 * 60)  # +東八區
        dat = "date %u-%02u-%02u" % (ttime.tm_year, ttime.tm_mon, ttime.tm_mday)
        tm = "time %02u:%02u:%02u" % (ttime.tm_hour, ttime.tm_min, ttime.tm_sec)
        return [dat, tm]

    '''
    修改時間1
    '''
    def setTime1(self,time_cls):
        ttime = time.localtime(time.mktime(time_cls) - 8 * 60 * 60)  # 本為東八區,卻set后多出8小時 UTC多了8個小時 , 所以……
        time_cls = ttime
        win32api.SetSystemTime(time_cls.tm_year, time_cls.tm_mon, time_cls.tm_wday, time_cls.tm_mday, time_cls.tm_hour, time_cls.tm_min, time_cls.tm_sec, 0)

    '''
    修改時間2
    '''
    def setTime2(self,time):
        os.system(time[0])
        os.system(time[1])



if __name__ == "__main__":
    classSyc = syctimes()
    # 方法1:
    #time_list = classSyc.getTime1()
    #classSyc.setTime1(time_list)

    # 方法2:
    # time_list = classSyc.getTime2('www.baidu.com')
    # classSyc.setTime2(time_list)
復制代碼

 

打包代碼為exe 添加隨系統啟動執行

import sys

if __name__ == '__main__':
    from PyInstaller import __main__
    params = ['-F', '-w', '--icon=favicon.ico', 'times.py']
    __main__.run(params)
復制代碼
# -*- coding:utf-8 -*-
import win32api
import win32con

name = 'SycTimeTool'  # 要添加的項值名稱
path = 'E:\dcb3688\時間同步工具.exe -1'  # 要添加的exe路徑
# 注冊表項名
KeyName = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run'
# 異常處理
try:
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,  KeyName, 0,  win32con.KEY_ALL_ACCESS)
    win32api.RegSetValueEx(key, name, 0, win32con.REG_SZ, path)
    win32api.RegCloseKey(key)
except:
    print('error')
print('添加成功!')
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM