使用 Python 脚本自动毫秒级精确同步系统时间

2018-02-25  本文已影响0人  ilwid

今天周末,把上周欠的时间同步脚本给大家补上,这个小脚本有以下特性:

没有多少技术含量,直接上代码了


# synctime.py

import os

import ntplib

import datetime

c = ntplib.NTPClient()

hosts = ['edu.ntp.org.cn', 'tw.ntp.org.cn', 'us.ntp.org.cn', 'cn.pool.ntp.org', 'jp.ntp.org.cn']

for host in hosts:

    try:

        response = c.request(host)

        if response:

            break

    except Exception as e:

        pass

current_time = response.tx_time

_date, _time = str(datetime.datetime.fromtimestamp(current_time))[:22].split(' ')

print("系统当前时间", str(datetime.datetime.now())[:22])

print("北京标准时间", _date, _time)

a, b, c = _time.split(':')

c = float(c) + 0.5

_time = "%s:%s:%s" % (a, b, c)

os.system('date %s && time %s' % (_date, _time))

print("同步后时间:", str(datetime.datetime.now())[:22])

# os.system("pause")


# 我家代码输出是这样的

>>> 2018-01-20 20:39:33.03

# 各位群众代码输出是这样的

>>> 2018-01-20 20:39:33

如果要每天自动对时,Win下直接按Win+R,输入taskschd.msc,在任务计划程序新建一个计划,按步骤选择脚本设置即可,不再赘述。

本文作者:盛开

本文链接: https://www.ilwid.net/posts/a2465ac4.html

**版权声明: **本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!

上一篇 下一篇

猜你喜欢

热点阅读