• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python获取网络时间和本地时间

python 搞代码 4年前 (2022-01-09) 46次浏览 已收录 0个评论

今天我们来看一下如何用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))     #设置日<strong style="color:transparent">本文来源gao@daima#com搞(%代@#码@网&</strong>期         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])

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python获取网络时间和本地时间
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址