Windows一用就是几年,总会碰到个更改系统时间的时候。可是把系统时间调坏了容易,要调出个正确可就没那么简单了。几年前(还上大学的时候,大概是大三吧)用C#写过一个ntp的程序,但是时过境迁,NTP的IP更改实在太频繁了(难道是因为没有商业利润?);windows的“Internet 时间”我从来就没有试成功过(有人知道why嘛?);国家授时中心(http://www.time.ac.cn)的什么时间精灵自从windows变sp2后在我的电脑上也不能用了----这算什么时代?。

看来,无奈下只好找个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网络校时失败,请检查网络!'

因为设置了超时时间仅为0.3秒,所以我想无论如何这样的时间精度都是可以接受的。实际上,在我的测试中即使设置timeout=0.01的情况下也没有出现过超时错误----当然,我是在北京试的。

相关文章: