Python 时间同步程序

Python 时间同步程序

两种修改本地时间的方法

(局域网内,利用网关服务器,穿越代理,与互联网时间同步的方法:
前部分用于win7系统,后部分用于winserver2008。
需要 pip3 install ntplib
需要启动Windows Time服务。)

import win32api
import datetime
import os
import time
import ntplib

def SetClockL():  # os.system
    try:
        c = ntplib.NTPClient()
        response = c.request('ntp1.aliyun.com')  
        ts = response.tx_time
        # _date = time.strftime('%Y-%m-%d', time.localtime(ts))
        # _time = time.strftime('%X', time.localtime(ts))
        _date, _time = str(datetime.datetime.fromtimestamp(ts))[:22].split(' ')
        print("调整前时间是:", datetime.datetime.now())
        os.system('date {} && time {}'.format(_date, _time))
        print("调整后时间是:", datetime.datetime.now())
    except Exception as e:
        print("SetClockL Get Error!", e)
    else:
        print("Set System OK!" + 'date {} && time {}'.format(_date, _time))


def SetClock():  # win32api
    try:
        client = ntplib.NTPClient()
        response = client.request('ntp.api.bz')
        print(datetime.datetime.fromtimestamp(response.tx_time))
        # print(time.gmtime(response.tx_time))
        tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.gmtime(
            response.tx_time)
        win32api.SetSystemTime(tm_year, tm_mon, tm_wday,
                               tm_mday, tm_hour, tm_min, tm_sec, 0)
        print("SetSystemTime OK!")
    except Exception as e:
        print("SetClockL Get Error!", e)
    else:
        print('Local Time new: ' +
              time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))


if __name__ == "__main__":
    SetClock()
    print("----\n")
    SetClockL()
    # a = input("\n按回车退出!\n")

运行结果

2022-01-05 16:04:53.053717
SetSystemTime OK!
Local Time new: 2022-01-05 16:04:53
----

调整前时间是: 2022-01-05 16:04:53.044000
调整后时间是: 2022-01-05 16:04:53.019000
Set System OK!date 2022-01-05 && time 16:04:53.12
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值