清风竹林

ぷ雪飘绛梅映残红
   ぷ花舞霜飞映苍松
     ----- Do more,suffer less

网络校时 python

   由于手动调整和计算机时钟精度的问题,我的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年。

  

posted on 2008-12-16 16:53 李现民 阅读(852) 评论(0)  编辑 收藏 引用 所属分类: minitools


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理