本文实例讲述了python获取标准北京时间的方法。分享给大家供大家参考。具体分析如下:
这段python代码主要通过www.beijing-time.org的官网上获取标准的北京时间,如果你的服务器挂在网上,你可以通过这段代码定时获取北京时间,然后更新自己系统的标准时间。
import time,httplib
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()
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:
return none
if __name__==’__main__’:
print(getbeijintime())
希望本文所述对大家的python程序设计有所帮助。