python实现定时同步本机与北京时间的方法
作者:八大山人 时间:2021-03-24 10:58:14
本文实例讲述了python实现定时同步本机与北京时间的方法。分享给大家供大家参考。具体如下:
这段python代码首先从www.beijing-time.org上获取标准的北京时间,然后同步获取的北京时间到本地
# -*- coding: utf-8 -*-
import time,httplib
import threading
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
def syncLocalTime():
"""
同步本地时间
"""
beijinTime = getBeijinTime()
if beijinTime is None:
timer = threading.Timer(30.0, syncLocalTime)
timer.start()
else:
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))#设置时间
if __name__=='__main__':
while True:
syncLocalTime()
time.sleep(30)
希望本文所述对大家的Python程序设计有所帮助。
标签:python,定时,同步,时间
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python爬虫框架Scrapy基本应用学习教程
2021-04-05 13:09:44
![](https://img.aspxhome.com/file/2023/8/94108_0s.png)
Python爬取商家联系电话以及各种数据的方法
2023-07-24 18:39:38
![](https://img.aspxhome.com/file/2023/0/66450_0s.jpg)
百度百科的图片轮播代码
2009-05-06 12:58:00
python 并发下载器实现方法示例
2022-03-31 10:46:00
Python中模块与包有相同名字的处理方法
2021-11-16 07:58:34
Python socket如何解析HTTP请求内容
2022-05-06 20:09:23
Pycharm中安装pywin32报错问题及解决
2022-09-29 19:58:14
![](https://img.aspxhome.com/file/2023/6/99116_0s.png)
Python实现简单图像缩放与旋转
2022-02-19 05:48:17
![](https://img.aspxhome.com/file/2023/8/92168_0s.png)
重构中的模块化设计:样式的作用域
2010-04-23 14:42:00
如何将 Access 的 Memo 型态字段汇入到 SQL2005 的 nvarchar 型态字段
2008-12-26 18:13:00
python里使用正则表达式的组嵌套实例详解
2021-05-09 18:11:34
RC4经典加密算法asp/VBs版本代码
2008-02-17 17:32:00
Python+OCR实现文档解析的示例代码
2023-11-22 02:34:19
![](https://img.aspxhome.com/file/2023/0/82790_0s.jpg)
python之模拟鼠标键盘动作具体实现
2022-12-23 10:51:29
python ChainMap的使用和说明详解
2022-03-03 08:22:30
php7安装openssl扩展方法
2023-11-14 17:34:14
Python求解任意闭区间的所有素数
2023-10-12 00:07:12
Dreamweaver制作技巧四则
2008-01-04 09:42:00
jQuerify书签
2008-06-16 12:16:00
python使用arcpy.mapping模块批量出图
2021-03-12 04:28:15