Python使用ntplib同步PC的时间和日期 20181022

使用python同步PC本地时间

最近安装了ubuntu系统,但是出现在ubuntu下的时间是准确的,但是Windows10下的时间不准。
Windows下的时间慢8h,估计是因为时区的原因导致的,想到能不能通过python来设置pc的时间呢,实现自动校准时间。
查阅了相关的资料:可以使用ntplib来实现


一、思路

通过获取网络时间,然后通过本机设置网络时间,达到同步的目的。
主要分为两个部分:

1.1、获取网络时间

1.1.1需要使用一个包:ntplib

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

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

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

1.1.2安装ntplib

使用pip在windows的cmd下安装,如果没有安装pip可以上网搜索下pip的安装方法。

pip install ntplib

1.1.3 ntplib的用法

1.1.3.1官方的例子:https://pypi.org/project/ntplib/

Example

>>> import ntplib
>>> from time import ctime
>>> c = ntplib.NTPClient()
>>> rense = c.request('europe.pool.ntp.org', version=3)
>>> respo.offset
-0.143156766891
>>> responsersion
3
>>> ctime(respo.tx_time)
'Sun May 17 09:32:48 2009'
>>> ntplib.leap_toxt(response.leap)
'no warning'
>>> response.root_delay
0.0046844482421875
>>> ntplib.ref_id_to_text(response.ref_id)
193.190.230.66
1.1.3.2 帮助和说明

可以通过ntplib.NTPClient.request来获取ntp server的相关信息

request(self, host, version=2, port='ntp', timeout=5)

return的值是NTPStats的对象

而 NTPStats是一个NTP统计的类,继承了NTPPacket。
其中有一个成员是tx_time,是server发射方的时间戳在本机系统上的时间。
写一个看下:

c = ntplib.NTPClient() #创建一个NTPClient的实例
s = c.request(ntp_server_url) #通过对象的request方法得到NTPStats的对象
s.tx_time # 访问对象中的tx_time成员,即是server的发射时间
1540136943.6524057

至此已经成功从ntp server上获取到了信息,这里用的ntp server是阿里云的地址,ntp5.aliyun.com,当然也可以用其他的ntp server。

1.2、设置本机的时间

通过os.system()来执行win下的time方法

不过好像Windows10没有权限修改时间,需要用admin来执行cmd

repl下用python写一个修改时间的先试看看。

import os
os.system('time {}'.format(19.01))

但是会遇到权限的问题,需要管理员权限才能修改,尝试用管理员运行下看看。

管理员是可以运行的,那写好的程序就只能通过管理员的cmd来执行,网上查找了有解决方法,但是没有实验,相关链接如下:

https://testerhome.com/topics/11793?locale=en

二、编写代码

import os
import ntplib
import time

ntp_server_url = 'ntp5.aliyun.com'


def get_ntp_time(ntp_server_url):
    """
    通过ntp server获取网络时间
    :param ntp_server_url: 传入的服务器的地址
    :return: time.strftime()格式化后的时间和日期
    """

    ntp_client = ntplib.NTPClient()
    ntp_stats = ntp_client.request(ntp_server_url)
    fmt_time = time.strftime('%X', time.localtime(ntp_stats.tx_time))
    fmt_date = time.strftime('%Y-%m-%d', time.localtime(ntp_stats.tx_time))
    return fmt_time, fmt_date


def set_system_time(new_time, new_date):
    """
    通过os.system来设置时间,需要管理员权限
    :param new_time:
    :param new_date
    :return: 无返回值
    """
    os.system('time {}'.format(new_time))
    os.system('date {}'.format(new_date))


if __name__ == '__main__':
    ntp_server_time, ntp_server_date = get_ntp_time(ntp_server_url)
    set_system_time(ntp_server_time, ntp_server_date)
    print('时间已经与{}同步'.format(ntp_server_url))

猜你喜欢

转载自www.cnblogs.com/yangfan2018/p/9833956.html
今日推荐