由于手動(dòng)調(diào)整和計(jì)算機(jī)時(shí)鐘精度的問題,我的windows時(shí)間經(jīng)常需要校正。以前用c#寫過一個(gè)ntp的時(shí)間校正工具,為此從網(wǎng)上找了好多ntp server的ip地址,但最終發(fā)現(xiàn)漸漸的它們都不能用了。后來慢慢地感覺到自己對(duì)系統(tǒng)時(shí)鐘的要求也沒那么精確,于是開始打web server的主意:通常web server,特別是一些比較著名的網(wǎng)站的server總有一些是在線的。
代碼似乎也不是很復(fù)雜,基于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('網(wǎng)絡(luò)校時(shí)成功!')
except Exception as ex:
print(ex)
print('網(wǎng)絡(luò)校時(shí)失敗')
return False
return True
def printCurTime():
now= time.localtime(time.time())
print('當(dāng)前系統(tǒng)時(shí)間:', time.strftime("%Y-%m-%d %H:%M:%S", now))
if __name__=='__main__':
printCurTime()
if updateSystemTime():
printCurTime()
保存文件名為updateTime.py,放入某個(gè)系統(tǒng)目錄,在命令行中測(cè)試如下:
C:\>updatetime
當(dāng)前系統(tǒng)時(shí)間: 2009-12-16 16:51:11
網(wǎng)絡(luò)校時(shí)成功!
當(dāng)前系統(tǒng)時(shí)間: 2008-12-16 16:51:12
C:\>
之前,我故意把時(shí)間調(diào)整到了2009年。