Below is a Python script that does what you described. It relies on detecting the operating system, finding the local timezone, fetching the current date and time from worldtimeapi.org, and updating the system time and date accordingly. Note that setting the system date and time usually requires elevated permissions, so you'll likely have to run this script with sudo on Linux or with administrative privileges on Windows.
import os
import platform
import subprocess
import requests
def get_os():
os_name = platform.system()
if os_name == 'Linux':
return 'Linux'
elif os_name == 'Windows':
return 'Windows'
else:
raise RuntimeError('Unsupported OS')
def get_timezone():
if os_name == 'Linux':
# Read timezone from /etc/timezone (works for many Linux distros)
try:
with open('/etc/timezone') as f:
return f.read().strip()
except IOError:
# Fallback to reading from /etc/localtime symlink
return os.path.realpath('/etc/localtime').split('/')[-2]
elif os_name == 'Windows':
# Use tzutil command (requires Windows 10 or later)
output = subprocess.check_output('tzutil /g', shell=True).decode().strip()
# Convert Windows timezone to IANA timezone format
timezone_map = {
'UTC': 'Etc/UTC',
'Pacific Standard Time': 'America/Los_Angeles',
# Add more mappings as necessary
}
return timezone_map.get(output, output)
def fetch_current_time(timezone):
url = f'https://worldtimeapi.org/api/timezone/{timezone}'
response = requests.get(url)
response.raise_for_status()
return response.json()['datetime']
def set_system_time(os_name, datetime_str):
if os_name == 'Linux':
date_time_format = '%Y-%m-%dT%H:%M:%S'
try:
time_str = datetime_str.split('.')[0]
subprocess.run(['sudo', 'date', '--set', time_str], check=True)
print(f"System time set to {time_str}")
except subprocess.CalledProcessError as e:
print(f"Failed to set time: {e}")
elif os_name == 'Windows':
date_time_format = '%Y-%m-%d %H:%M:%S'
try:
date_str, time_str = datetime_str.split('.')[0].split('T')
subprocess.run(['powershell', f'Set-Date "{date_str} {time_str}"'], check=True)
print(f"System time set to {date_str} {time_str}")
except subprocess.CalledProcessError as e:
print(f"Failed to set time: {e}")
if __name__ == '__main__':
os_name = get_os()
timezone = get_timezone()
current_time = fetch_current_time(timezone)
set_system_time(os_name, current_time)
Instructions:
-
Run the script with elevated privileges:
- Linux: Use
sudo:
sudo python3 set_time.py
- Windows: Run the script from a command prompt with administrative privileges.
-
Adapt the timezone mapping (Windows specific): The script includes basic timezone mappings. You might need to expand this mapping to cover all possible values of tzutil /g output.
-
Error Handling:
- The script tries to handle file reading errors and subprocess errors but might need additional enhancement for robustness.
-
Dependencies: Ensure that the requests library is installed:
pip install requests
Remember to make a backup of any critical data before running scripts that modify system settings.