這篇文章主要介紹了python實現定時同步本機與北京時間的方法,涉及Python針對時間的操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了python實現定時同步本機與北京時間的方法。分享給大家供大家參考。具體如下:
這段python代碼首先從www.beijing-time.org上獲取標准的北京時間,然後同步獲取的北京時間到本地
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 # -*- 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("rn") 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程序設計有所幫助。