首页 > 代码库 > windows时间同步脚本

windows时间同步脚本

#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# 脚本用于windows时间同步,设置window计划任务每五分钟执行一次

import time
import ntplib
import sys
import os


def main():
try:
ntp_client = ntplib.NTPClient()
response = ntp_client.request(‘s2g.time.edu.cn‘)
ntp_timeStamp = response.tx_time
ntp_date = time.strftime(‘%Y-%m-%d‘, time.localtime(ntp_timeStamp))
ntp_time = time.strftime(‘%X‘, time.localtime(ntp_timeStamp))
except:
print u‘无法获取到s2g.time.edu.cn上面的时间戳‘
sys.exit()

‘‘‘获取本地服务器时间戳‘‘‘
local_timeStamp = time.time()

‘‘‘获取之间的差值‘‘‘
diff = abs(ntp_timeStamp - local_timeStamp)

‘‘‘同步时间‘‘‘
if diff >= 1:
os.system(‘date {} && time {}‘.format(ntp_date, ntp_time))

if __name__ == ‘__main__‘:
main()

windows时间同步脚本