Python 方式实现使用http时间同步设置系统时间源码,系统环境是ubuntu 12.04、Python2.7版本。需要使用到time、os及httplib方法。
Python使用http时间同步设置系统时间,源码如下:
`#-*-coding:utf8 -*-` `import` `httplib as client` `import` `time` `import` `os` `def` `get_webservertime(host):` `conn``=``client.HTTPConnection(host)` `conn.request(``"GET"``,` `"/"``)` `r``=``conn.getresponse()` `ts``=` `r.getheader(``'date'``)` `#获取http头date部分` `#将GMT时间转换成北京时间` `local_time``=` `time.mktime(time.strptime(ts[``5``:],` `"%d %b %Y %H:%M:%S GMT"``))` `+` `(``8` `*` `60` `*` `60``)` `ltime` `=` `time.gmtime(local_time)` `#使用date设置时间` `dat` `=` `'date -u -s "%d-%d-%d %d:%d:%d" '` `%` `(ltime.tm_year,ltime.tm_mon,ltime.tm_mday,ltime.tm_hour,ltime.tm_min,ltime.tm_sec)` `os.system(dat)` `get_webservertime(``'``)`
大家在学python的时候肯定会遇到很多难题,以及对于新技术的追求,这里推荐一下我们的Python学习扣qun:784758214,这里是python学习者聚集地!!同时,自己是一名高级python开发工程师,从基础的python脚本到web开发、爬虫、django、数据挖掘等,零基础到项目实战的资料都有整理。送给每一位python的小伙伴!每日分享一些学习的方法和需要注意的小细节
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69913713/viewspace-2648937/ ,如需转载,请注明出处,否则将追究法律责任。