Python 使用ntplib库同步校准当地时间的方法 (NTP)
生活随笔
收集整理的這篇文章主要介紹了
Python 使用ntplib库同步校准当地时间的方法 (NTP)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
NTP(Network Time Protocol)是由美國德拉瓦大學(xué)的David L. Mills教授于1985年提出,設(shè)計(jì)用來在Internet上使不同的機(jī)器能維持相同時(shí)間的一種通訊協(xié)定。
?
NTP估算封包在網(wǎng)絡(luò)上的往返延遲,獨(dú)立地估算計(jì)算機(jī)時(shí)鐘偏差,從而實(shí)現(xiàn)在網(wǎng)絡(luò)上的高精準(zhǔn)度計(jì)算機(jī)校時(shí)。
NTP服務(wù)在Linux系統(tǒng)比較常見,其實(shí)Python也一樣,可網(wǎng)上搜索"python獲取時(shí)間"時(shí),很多是解析頁面獲取時(shí)間的笨辦法,殊不知Python也可使用NTP服務(wù)進(jìn)行時(shí)間同步獲取精確時(shí)間、只需要使用ntplib庫即可實(shí)現(xiàn)。
?
ntplib庫用法簡介
安裝ntplib:
easy_install ntplib
或
pip install ntplib
代碼解釋:
import os import time import ntplib c = ntplib.NTPClient() response = c.request('pool.ntp.org') ts = response.tx_time _date = time.strftime('%Y-%m-%d',time.localtime(ts)) _time = time.strftime('%X',time.localtime(ts)) os.system('date {} && time {}'.format(_date,_time))?
源碼實(shí)例:
#用于檢查時(shí)間偏移的函數(shù) def check_time(self):#確保我們的蜜罐時(shí)間是一致的,與實(shí)際時(shí)間相差不太遠(yuǎn)。poll = self.config['timecheck']['poll']ntp_poll = self.config['timecheck']['ntp_pool']while True:clnt = ntplib.NTPClient()try:response = clnt.request(ntp_poll, version=3)diff = response.offsetif abs(diff) >= 15:logger.error('Timings found to be far off, shutting down drone ({0})'.format(diff))sys.exit(1)else:logger.debug('Polled ntp server and found that drone has {0} seconds offset.'.format(diff))except (ntplib.NTPException, _socket.error) as ex:logger.warning('Error while polling ntp server: {0}'.format(ex))gevent.sleep(poll * 60 * 60)?
總結(jié)
以上是生活随笔為你收集整理的Python 使用ntplib库同步校准当地时间的方法 (NTP)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python__repr__()方法:显
- 下一篇: ubuntu安装java8