美文网首页大数据 爬虫Python AI Sql互联网科技码农的世界
【Python】Python 使用http时间同步设置系统时间源

【Python】Python 使用http时间同步设置系统时间源

作者: IT派森 | 来源:发表于2019-07-02 23:22 被阅读1次

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(``'www.baidu.com'``)`
Python资源分享Q群:855408893  内有安装包,学习视频资料,免费直播实战案例。这里是Python学习者的聚集地,零基础,进阶,都欢迎

相关文章

网友评论

    本文标题:【Python】Python 使用http时间同步设置系统时间源

    本文链接:https://www.haomeiwen.com/subject/lrraqctx.html