Skip to content

Instantly share code, notes, and snippets.

@nihal111
Last active October 29, 2021 07:05
Show Gist options
  • Save nihal111/7d95fa52fb91bf3298947cd36b700ce8 to your computer and use it in GitHub Desktop.
Save nihal111/7d95fa52fb91bf3298947cd36b700ce8 to your computer and use it in GitHub Desktop.
A python script to update time in Windows using HTTPS, when NTP is not working. Works on scraping duration since epoch time from www.unixtimestamp.com and uses win32api (earlier pywin32) to update the system time. Needs to be run with administrator permissions.
import requests
import datetime
import win32api
page = requests.get('https://www.unixtimestamp.com/', headers={'Cache-Control': 'no-cache'})
text = page.text
for line in text.split("\n"):
match_text = "<h3 class=\"text-danger\">"
suffix = " <small>seconds since Jan 01 1970. (UTC)</small></h3>"
if match_text in line:
line = line.replace('<',' ').replace('>',' ')
epoch_time = [int(s) for s in line.split() if s.isdigit()][0]
break
utcTime = datetime.datetime.utcfromtimestamp(epoch_time)
try:
# SetSystemTime takes time as argument in UTC time
win32api.SetSystemTime(utcTime.year, utcTime.month, utcTime.weekday(), utcTime.day, utcTime.hour, utcTime.minute, utcTime.second, 0)
localTime = datetime.datetime.fromtimestamp(epoch_time)
print("Time updated to: " + localTime.strftime("%Y-%m-%d %H:%M"))
except:
print("Could not update time")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment