Created
February 19, 2013 07:56
-
-
Save beordle/4983879 to your computer and use it in GitHub Desktop.
从 网络time.windows.com time.apple.com 校正时间
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from socket import * | |
import datetime,os,struct,time,sys | |
# Script to set Linux hardware clock (/usr/sbin/hwclock) from an NTP | |
# time server. Run as "setclock.py" to simply print the time from | |
# the NTP server. Run as "setclock.py --set" to set the Linux | |
# hardware clock (as the super user, of course). | |
# Based on Simon Foster's simple SNTP client from ASPN Python cookbook. | |
# Adapted by Paul Rubin; this script lives at: | |
# http://www.nightsong.com/phr/python/setclock.py | |
# time.apple.com is a stratum 2 time server. (123 is the SNTP port number). | |
# More servers info can be found at | |
# | |
# http://www.eecis.udel.edu/~mills/ntp/servers.htm | |
# | |
# Note it's considered antisocial to use a stratum 1 server (like NIST) | |
# for purposes like this which don't need extreme accuracy (i.e. syncing | |
# your own big NTP network). See www.ntp.org for more info. | |
# | |
# You could also use time.windows.com (Microsoft server) which syncs | |
# all Windows XP machines everywhere, so it can presumably handle lots | |
# of clients. | |
# number of seconds between NTP epoch (1900) and Unix epoch (1970). | |
time_server = ('time.windows.com', 123) | |
TIME1970 = 2208988800L | |
def getdatetime(): | |
client = socket( AF_INET, SOCK_DGRAM ) | |
data = '\x1b' + 47 * '\0' | |
client.sendto(data.encode(), 0, time_server) | |
data, address = client.recvfrom(1024) | |
if data: | |
t = struct.unpack( '!12I', data )[10] | |
if t == 0: | |
raise 'invalid response' | |
ct = time.ctime(t - TIME1970) | |
print 'Current time = %s\n' % ct | |
#os.system("/usr/sbin/hwclock --set '--date=%s'"% ct) | |
now = datetime.datetime | |
now = now.fromtimestamp(t - TIME1970) | |
return now | |
else: | |
raise 'no data returned' | |
now = getdatetime() | |
print(now) | |
time_server = ('time.apple.com', 123) | |
now = getdatetime() | |
print(now) | |
if len(sys.argv) > 1 and sys.argv[1] == "-set": | |
os.system('date ' + now.strftime('%Y-%m-%d')) | |
os.system('time ' + now.strftime('%H:%M:%S')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment