Heim  >  Artikel  >  Backend-Entwicklung  >  Python使用ntplib库同步校准当地时间的方法

Python使用ntplib库同步校准当地时间的方法

WBOY
WBOYOriginal
2016-07-22 08:56:352042Durchsuche

NTP(Network Time Protocol)是由美国德拉瓦大学的David L. Mills教授于1985年提出,设计用来在Internet上使不同的机器能维持相同时间的一种通讯协定。

NTP估算封包在网络上的往返延迟,独立地估算计算机时钟偏差,从而实现在网络上的高精准度计算机校时。

NTP服务在Linux系统比较常见,其实Python也一样,可网上搜索"python获取时间"时,很多是解析页面获取时间的笨办法,殊不知Python也可使用NTP服务进行时间同步获取精确时间、只需要使用ntplib库即可实现。

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)) 

这样便可以轻松同步当地时间了~

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn