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')