两种修改本地时间的方法
(局域网内,利用网关服务器,穿越代理,与互联网时间同步的方法:
前部分用于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