1. 首先需要安裝ntplib模塊
pip install ntplib
2.windows中獲取系統時間及對時
1 # 獲取系統日期(修改把/t改為日期字符串) 2 date /t 3 # 獲取系統時間(修改把/t改為時間字符串) 4 time /t
3.NTP對時的函數示例代碼
1 def ntp_timing(): 2 # 以阿里雲NTP對時服務器為例 3 response = ntplib.NTPClient().request('ntp.aliyun.com') 4 ts = response.tx_time 5 _date = time.strftime('%Y-%m-%d', time.localtime(ts)) 6 _time = time.strftime('%X', time.localtime(ts)) 7 os.system('date {} && time {}'.format(_date, _time)) 8 t1 = time.strftime('%Y-%m-%d %X', time.localtime(ts)) 9 t2 = datetime.datetime.now().strftime('%Y-%m-%d %X') 10 if t1 == t2: 11 print('NTP對時成功') 12 else: 13 print('NTP對時失敗')