今天我们来看一下如何用python获取网络时间和本地时间,直接上代码吧,代码中都有注释。
python获取网络时间
获取网络时间
def getbeijintime():
“””
获取北京时间
“””
try:
conn = httplib.httpconnection(“www.beijing-time.org”)
conn.request(“get”, “/time.asp”)
response = conn.getresponse()
print response.status, response.reason
if response.status == 200:
#解析响应的消息
result = response.read()
logging.debug(result)
data = result.split(“\r\n”)
year = data[1][len(“nyear”)+1 : len(data[1])-1]
month = data[2][len(“nmonth”)+1 : len(data[2])-1]
day = data[3][len(“nday”)+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获取本地时间
同步本地系统时间
def synclocaltime():
“””
同步本地时间
“””
logging.info(“current local time is: %d-%d-%d %d:%d:%d” % time.localtime()[:6])
beijintime = getbeijintime()
if beijintime is none:
logging.info(“get beijintime is none, will try again in 30 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])