- 1 year ago
How to get login and logout time in windows in python?
To get the login and logout time of a user in Windows using Python, you can utilize the WMI
(Windows Management Instrumentation) module. Here's an example code snippet:
pythonimport wmi
def get_user_login_logout_time():
# Connect to the WMI service
wmi_service = wmi.WMI()
# Get the Win32_ComputerSystem instance for the local machine
computer_system = wmi_service.Win32_ComputerSystem()[0]
# Get the LastBootUpTime (login time) and LocalDateTime (current time)
login_time = computer_system.LastBootUpTime.split('.')[0]
current_time = computer_system.LocalDateTime.split('.')[0]
# Calculate the duration in seconds
duration = (wmi_service.Win32_OperatingSystem()[0].LocalDateTime - wmi_service.Win32_OperatingSystem()[0].LastBootUpTime).seconds
return login_time, current_time, duration
# Usage
login_time, current_time, duration = get_user_login_logout_time()
print("Login Time:", login_time)
print("Current Time:", current_time)
print("Duration (seconds):", duration)
This code uses the wmi
module to connect to the Windows Management Instrumentation service and retrieves the LastBootUpTime
(login time) and LocalDateTime
(current time) from the Win32_ComputerSystem
class. It also calculates the duration of the current session in seconds.
Keep in mind that this approach provides the login time and current time of the local machine. If you need to retrieve the login and logout time for specific users, you may need to query the appropriate Windows event logs or utilize additional APIs, such as the NetUserGetInfo
function from the pywin32
module, to retrieve the required information.
Please note that accessing certain system information or event logs may require administrative privileges. Ensure that you run the script with the necessary permissions to retrieve the desired information.