Skip to content

Instantly share code, notes, and snippets.

@tcely
Last active April 19, 2025 02:10
Show Gist options
  • Save tcely/50c39e0589c9edc420eda434dbcdab41 to your computer and use it in GitHub Desktop.
Save tcely/50c39e0589c9edc420eda434dbcdab41 to your computer and use it in GitHub Desktop.
Getting Windows Last Boot Time in Python
#!/usr/bin/env python3
import datetime
import os
# import wmi
# https://github.com/tjguk/wmi
# https://github.com/tcely/wmi
class LastBoot:
_wmi_module = False
def _make_datetime_windows(self):
assert self._wmi_module, 'Install wmi using pip'
self.utc_offset = None
tzinfo = datetime.timezone.utc
c = wmi.WMI(find_classes=False)
for obj in c.Win32_OperatingSystem():
last_boot = obj.LastBootUpTime
tt = wmi.to_time(last_boot)
utc_offset_str = last_boot[21:]
try:
utc_offset = int(utc_offset_str, 10)
except (TypeError, ValueError):
pass
else:
self.utc_offset = datetime.timedelta(minutes=utc_offset)
tzinfo = datetime.timezone(self.utc_offset)
return datetime.datetime(*tt[0:6], tzinfo=tzinfo)
def _make_datetime(self):
if 'nt' == os.name:
return self._make_datetime_windows()
return datetime.datetime.now()
@property
def datetime(self):
self._datetime = self._make_datetime()
return self._datetime
try:
import wmi
except ModuleNotFoundError:
pass
else:
LastBoot._wmi_module = True
if '__main__' == __name__:
last_boot_dt = LastBoot().datetime
print( last_boot_dt.isoformat(timespec='seconds') )
class DummyObj():
pass
class DummyC():
def Win32_OperatingSystem(self):
obj = DummyObj()
obj.LastBootUpTime = '20250102123456.987654-120'
return list((obj,))
class DummyWMI():
def WMI(self, *args, **kwargs):
return DummyC()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment