Skip to content

Instantly share code, notes, and snippets.

@kde713
Last active January 6, 2019 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kde713/26815746d419dbaa10dee5b73bb2bed4 to your computer and use it in GitHub Desktop.
Save kde713/26815746d419dbaa10dee5b73bb2bed4 to your computer and use it in GitHub Desktop.
Force Syncing System time (When NTP Not available)
import sys
from datetime import datetime
import fire
import requests
class SyncError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
def __repr__(self):
return f"SyncError('{self.message}')"
class WorldTimeApiClient:
def get_api_datetime(self, tz: str) -> datetime:
response = requests.get("http://worldtimeapi.org/api/timezone/" + tz)
data = response.json()
if data.get("error"):
raise SyncError("API Error: " + response.json()['error'])
return datetime.fromisoformat(response.json()['datetime'])
class TimeSyncApplication:
def view(self):
client = WorldTimeApiClient()
sys.stdout.write(client.get_api_datetime("UTC").isoformat())
def sync(self):
client = WorldTimeApiClient()
server_time = client.get_api_datetime("UTC")
if sys.platform == "win32":
from win32 import win32api
win32api.SetSystemTime(server_time.year, server_time.month, server_time.isocalendar()[2], server_time.day, server_time.hour, server_time.minute, server_time.second, 0)
else:
raise SyncError("Not supported platform: " + str(sys.platform))
if __name__ == "__main__":
fire.Fire(TimeSyncApplication)
@kde713
Copy link
Author

kde713 commented Jan 6, 2019

requirements

pywin32==224
requests==2.21.0
fire==0.1.3

@kde713
Copy link
Author

kde713 commented Jan 6, 2019

Usage Example

python app.py sync

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment