如何获取Windows系统运行时长?求CMD命令或Python实现方案
获取Windows系统运行时长(类似Linux
uptime -p 的实现) 一、Shell命令实现(可通过Python调用)
用PowerShell可以直接计算并输出格式化的运行时长,命令如下:
$bootTime = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime $uptime = (Get-Date) - $bootTime $output = "up $($uptime.Days) days, $($uptime.Hours) hours, $($uptime.Minutes) minutes" Write-Output $output
如果要在CMD中执行,可嵌套调用PowerShell:
powershell -Command "$bootTime=(Get-CimInstance Win32_OperatingSystem).LastBootUpTime;$uptime=(Get-Date)-$bootTime;Write-Output 'up $($uptime.Days) days, $($uptime.Hours) hours, $($uptime.Minutes) minutes'"
Python调用Shell命令获取输出
使用subprocess模块执行上述命令并捕获结果:
import subprocess def get_windows_uptime_shell(): cmd = '''powershell -Command "$bootTime=(Get-CimInstance Win32_OperatingSystem).LastBootUpTime;$uptime=(Get-Date)-$bootTime;Write-Output 'up $($uptime.Days) days, $($uptime.Hours) hours, $($uptime.Minutes) minutes'"''' result = subprocess.run(cmd, shell=True, capture_output=True, text=True) if result.returncode == 0: return result.stdout.strip() else: return f"Error: {result.stderr.strip()}" print(get_windows_uptime_shell())
二、Python原生实现(推荐)
方案1:使用psutil库(跨平台,简洁)
psutil是跨平台系统信息库,可直接获取启动时间并计算运行时长:
- 先安装库(若未安装):
pip install psutil
- 实现代码:
import psutil from datetime import datetime def get_windows_uptime_psutil(): boot_time = datetime.fromtimestamp(psutil.boot_time()) uptime = datetime.now() - boot_time days = uptime.days hours, remainder = divmod(uptime.seconds, 3600) minutes = remainder // 60 return f"up {days} days, {hours} hours, {minutes} minutes" print(get_windows_uptime_psutil())
方案2:纯原生Python(无第三方库)
通过ctypes调用Windows API获取系统运行毫秒数,再转换为格式化时长:
import ctypes from datetime import timedelta def get_windows_uptime_native(): kernel32 = ctypes.WinDLL('kernel32') uptime_ms = kernel32.GetTickCount64() uptime = timedelta(milliseconds=uptime_ms) days = uptime.days hours = uptime.seconds // 3600 minutes = (uptime.seconds % 3600) // 60 return f"up {days} days, {hours} hours, {minutes} minutes" print(get_windows_uptime_native())
内容的提问来源于stack exchange,提问作者justanormaluser
相关产品推荐
相关产品推荐

