python 获取网络时间及修改本地时间
- 2020 年 1 月 10 日
- 筆記
python 获取网络时间及修改本地时间
本本经常时间错乱,偶闲暇之作,专为同步本本时间。以前有朋友提到日期时间设置里面的有些时间服务器。限于不同的网络,有时候这些时间服务器不一定能用。因此这次选择的是www.baidu.com这个大家都能用吧。接下来上python代码 :}
1 import http.client 2 import time 3 import os 4 def get_webservertime(host): 5 conn=http.client.HTTPConnection(host) 6 conn.request("GET", "/") 7 r=conn.getresponse() 8 #r.getheaders() #获取所有的http头 9 ts= r.getheader('date') #获取http头date部分 10 #将GMT时间转换成北京时间 11 ltime= time.strptime(ts[5:25], "%d %b %Y %H:%M:%S") 12 print(ltime) 13 ttime=time.localtime(time.mktime(ltime)+8*60*60) 14 print(ttime) 15 dat="date %u-%02u-%02u"%(ttime.tm_year,ttime.tm_mon,ttime.tm_mday) 16 tm="time %02u:%02u:%02u"%(ttime.tm_hour,ttime.tm_min,ttime.tm_sec) 17 print (dat,tm) 18 os.system(dat) 19 os.system(tm) 20 21 get_webservertime('www.baidu.com')