工作用的Windows平台电脑时间老是不准,影响很多程序的正常运行,于是网上搜索了段可用的代码用于自动同步。
程序需要ntplib库用ntp协议从pool.ntp.org获取时间,需要安装ntpli库,开始用pip install ntplib命令安装老提示以下错误信息:
1 2 | ERROR: Could not find a version that satisfies the requirement ntplib ERROR: No matching distribution found for ntplib |
可以测试用命令:
#C:\>pip install lightgbm -i http://pypi.douban.com/simple –trusted-host pypi.douban.com
1 | C:\>pip install ntplib -i http://pypi.douban.com/simple --trusted-host pypi.douban.com |
不然就用 easy_install ntplib 方式安装!
程序代码:
1 2 3 4 5 6 7 8 9 10 11 12 | # coding="utf-8"
import time
import os
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))
print("Response Offset: ", response.offset)
os.system('date {} && time {}'.format(_date,_time))
print("itkylin_py_rsynctime_finished") |
执行:
Python itkylin_py_rsynctime.py