由于手動調整和計算機時鐘精度的問題,我的windows時間經常需要校正。以前用c#寫過一個ntp的時間校正工具,為此從網上找了好多ntp server的ip地址,但最終發現漸漸的它們都不能用了。后來慢慢地感覺到自己對系統時鐘的要求也沒那么精確,于是開始打web server的主意:通常web server,特別是一些比較著名的網站的server總有一些是在線的。
代碼似乎也不是很復雜,基于python 3.0---
import time
import urllib.request
import urllib.parse
import ctypes
SetSystemTime = ctypes.windll.kernel32.SetSystemTime
GetSystemTime = ctypes.windll.kernel32.GetSystemTime
class SYSTEMTIME(ctypes.Structure):
c_ushort= ctypes.c_ushort
_fields_ = (
('wYear', c_ushort),
('wMonth', c_ushort),
('wDayOfWeek', c_ushort),
('wDay', c_ushort),
('wHour', c_ushort),
('wMinute', c_ushort),
('wSecond', c_ushort),
('wMilliseconds', c_ushort),
)
def __str__(self):
return '%4d%02d%02d%02d%02d%02d.%03d' % (self.wYear,self.wMonth,self.wDay,self.wHour,self.wMinute,self.wSecond,self.wMilliseconds)
def updateSystemTime():
url= 'http://www.baidu.com'
try:
response= urllib.request.urlopen(url)
header= response.info()
date=header['Date']
gmt=time.strptime(date[5:25], "%d %b %Y %H:%M:%S")
st=SYSTEMTIME(gmt.tm_year,gmt.tm_mon,gmt.tm_wday,gmt.tm_mday,gmt.tm_hour,gmt.tm_min,gmt.tm_sec,0)
SetSystemTime(ctypes.byref(st))
print('網絡校時成功!')
except Exception as ex:
print(ex)
print('網絡校時失敗')
return False
return True
def printCurTime():
now= time.localtime(time.time())
print('當前系統時間:', time.strftime("%Y-%m-%d %H:%M:%S", now))
if __name__=='__main__':
printCurTime()
if updateSystemTime():
printCurTime()
保存文件名為updateTime.py,放入某個系統目錄,在命令行中測試如下:
C:\>updatetime
當前系統時間: 2009-12-16 16:51:11
網絡校時成功!
當前系統時間: 2008-12-16 16:51:12
C:\>
之前,我故意把時間調整到了2009年。