Today, let's take a look at how to get network time and local time in Python, directly on the code, with comments in the code.
Python Gets network time
Get Network Time Def getbeijintime (): "" "" "to get the Beijing Times" "" Try:conn = Httplib. Httpconnection ("www.beijing-time.org") conn.request ("GET", "/time.asp") response = Conn.getresponse () Print Response.Status, response.reason if response.status = =: #解析响应的消息 result = re Sponse.read () logging.debug (result) data = Result.split ("\ r \ n") year = Data[1][len ("NY Ear ") +1:len (Data[1])-1] month = Data[2][len (" Nmonth ") +1:len (Data[2])-1] day = Data[3][len (" NDA Y ") +1:len (Data[3])-1] #wday = Data[4][len (" Nwday ") +1:len (Data[4])-1] hrs = Data[5][len (" nhrs ") +1:len (Data[5])-1] minute = Data[6][len ("Nmin") +1:len (Data[6])-1] sec = Data[7][len ("nsec") +1 : Len (Data[7])-1] beijintimestr = "%s/%s/%s%s:%s:%s"% (year, month, day, hrs, minute, sec) Beijintime = Time.strptime (Beijintimestr, "%y/%m/%D%x ") return beijintime except:logging.exception (" Getbeijintime except ") return None
Python gets local time
Synchronize Local System time Def synclocaltime (): "" " Synchronize local time" "" Logging.info ("current local times is :%d-%d-%d%d:%d:%d"% Time.localtime () [: 6]) beijintime = Getbeijintime () if Beijintime is None: logging.info ("Get Beijintime" is None, would try again in seconds ... ") timer = Threading. Timer (30.0, Synclocaltime) Timer.start (); else: logging.info ("Get Beijintime is:%d-%d-%d%d:%d:%d"% beijintime[:6]) tm_year, Tm_mon, Tm_mday, Tm_hour , tm_min, tm_sec = beijintime[:6] import os os.system ("date%d-%d-%d"% (Tm_year, Tm_mon, Tm_mday)) #设置日期 Os.system ("Time%d:%d:%d.0"% (Tm_hour, tm_min, tm_sec)) #设置时间 logging.info ("Synclocaltime complete, Current local time:%d-%d-%d%d:%d:%d \ n "%time.localtime () [: 6])