python-电脑时间校准

python-电脑时间校准源码

#-*- coding = utf-8 -*-
#Time : 2021/1/22 
#Author : 小柠檬
#File : 时间校准.py
import ntplib
import os
import datetime
import time

def ntpClient():
    hosts = ['0.cn.pool.ntp.org', '1.cn.pool.ntp.org', '2.cn.pool.ntp.org', '3.cn.pool.ntp.org']
    t = ntplib.NTPClient()

    for host in hosts:
        try:
            r = t.request(host, port='ntp', version=4, timeout=5)

            if r:
                t = r.tx_time
                _date, _time = str(datetime.datetime.fromtimestamp(t))[:22].split(' ')
                os.system('date {} && time {}'.format(_date, _time))
                print('\r',time.strftime('%Y-%m-%d %H:%M:%S'),'时间校准成功',end='')
                break

        except Exception as e:
            pass

if __name__ == '__main__':
    while True:
        ntpClient()

你可能感兴趣的:(python-电脑时间校准,python)