每次开机启动windows,时间都是错的,忍无可忍,python更新windows时间解决方案:
安装ntplib库:python -m pip install ntplib
# 导入ntplib (Network Time Protocol) 网络时间协议
import subprocess
import time
from datetime import datetime
import ntplib
ntp_servers = [
"time.windows.com",
"pool.ntp.org",
"time.cloudflare.com",
"time.nist.gov",
"time.amazon.com",
]
def get_window_time(servers):
for i in range(10, 0, -1):
print(f"等待windows启动{i}秒 ", end="\r")
time.sleep(1)
print(" ")
for server in servers:
try:
print(f"正在从服务器`{server}`获取时间数据...")
client = ntplib.NTPClient()
response = client.request(server)
ntp_time = datetime.fromtimestamp(response.tx_time)
return ntp_time
except Exception as e:
print(f"服务器{server}返回错误信息:{e}")
return None
def set_window_time(new_time):
try:
print("更新windows时间...")
formatted_time = new_time.strftime("%H:%M:%S")
subprocess.run(["time", f"{formatted_time}"], shell=True, check=True)
except Exception as e:
print(f"更新系统时间失败:{e}")
if __name__ == "__main__":
new_time = get_window_time(ntp_servers)
if new_time:
set_window_time(new_time)
else:
print("获取网络时间服务器数据失败,请检查网络")