看来,无奈下只好找个http服务器来进行网络校时了?反正像我们这种凡人也不需要那种不差毫厘的时间,再说就凭windows那种时间精度,唉,啥也不说了.........
import socket,urllib2,win32api,time
def updateSysTime():
try:
srv=urllib2.urlopen('http://www.baidu.com')
date=srv.headers.dict['date']
gmt=time.strptime(date[5:25], "%d %b %Y %H:%M:%S")
## SetSystemTime函数的参数是使用gmt时间
return win32api.SetSystemTime(gmt.tm_year,gmt.tm_mon,gmt.tm_wday,gmt.tm_mday,gmt.tm_hour,gmt.tm_min,gmt.tm_sec,0)
except:
return 0
def printCurTime():
now = time.localtime(time.time())
print time.strftime("%Z %Y-%m-%d %H:%M:%S", now)
##超时时间,以 秒 为单位
timeout=0.3
socket.setdefaulttimeout(timeout)
print u'当前系统时间:'
printCurTime()
print '\r\n'
i,maxTry=1,6
while i<maxTry and updateSysTime()==0:
print u'网络超时,第%i次重试'%i
i=i+1
if i<maxTry:
print u'网络校时成功:'
printCurTime()
else:
print u'\r\n网络校时失败,请检查网络!'
def updateSysTime():
try:
srv=urllib2.urlopen('http://www.baidu.com')
date=srv.headers.dict['date']
gmt=time.strptime(date[5:25], "%d %b %Y %H:%M:%S")
## SetSystemTime函数的参数是使用gmt时间
return win32api.SetSystemTime(gmt.tm_year,gmt.tm_mon,gmt.tm_wday,gmt.tm_mday,gmt.tm_hour,gmt.tm_min,gmt.tm_sec,0)
except:
return 0
def printCurTime():
now = time.localtime(time.time())
print time.strftime("%Z %Y-%m-%d %H:%M:%S", now)
##超时时间,以 秒 为单位
timeout=0.3
socket.setdefaulttimeout(timeout)
print u'当前系统时间:'
printCurTime()
print '\r\n'
i,maxTry=1,6
while i<maxTry and updateSysTime()==0:
print u'网络超时,第%i次重试'%i
i=i+1
if i<maxTry:
print u'网络校时成功:'
printCurTime()
else:
print u'\r\n网络校时失败,请检查网络!'
因为设置了超时时间仅为0.3秒,所以我想无论如何这样的时间精度都是可以接受的。实际上,在我的测试中即使设置timeout=0.01的情况下也没有出现过超时错误----当然,我是在北京试的。