Skip to content

Instantly share code, notes, and snippets.

@Kerrigan29a
Last active August 17, 2017 11:31
Show Gist options
  • Save Kerrigan29a/29f53ea575409f83c2056bb4283b3afc to your computer and use it in GitHub Desktop.
Save Kerrigan29a/29f53ea575409f83c2056bb4283b3afc to your computer and use it in GitHub Desktop.
Script to update datetime when its not possible to connect to NTP servers
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import sys
from datetime import datetime, timedelta
import os
import time
def update_local_time():
# Get datetime
dt = urllib2.urlopen("http://www.google.com").headers.dict["date"]
print dt
dt = datetime.strptime(dt, "%a, %d %b %Y %H:%M:%S %Z")
# Set UTC time
print "Setting UTC time to {}".format(dt)
txt = dt.strftime("%m%d%H%M%y")
r = os.system("date " + txt)
# Guess UTC offset
is_dst = time.daylight and time.localtime().tm_isdst > 0
utc_offset = - (time.altzone if is_dst else time.timezone)
if utc_offset:
dt += timedelta(seconds=utc_offset)
# Set Local time
print "Setting Local time to {}".format(dt)
txt = dt.strftime("%m%d%H%M%y")
r = os.system("date " + txt)
return r
def check_root():
return os.getuid() == 0
if __name__ == "__main__":
if check_root():
r = update_local_time()
else:
print "To run this script you need admin rights"
r = 1
sys.exit(r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment