Created
February 20, 2013 12:12
-
-
Save beordle/4995110 to your computer and use it in GitHub Desktop.
时间 网络
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
# -*- coding: utf-8 -*- | |
import socket,sys,time | |
#时间服务器 | |
host = "stdtime.gov.hk" | |
#端口 | |
port = 37 | |
#时区 | |
curtz = 8 | |
#连接服务器,并接收返回 | |
try: | |
host = socket.gethostbyname(host) | |
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) | |
s.settimeout(2) | |
s.sendto("",(host,port)) | |
buf = s.recvfrom(10)[0] | |
except socket.timeout,ex: | |
print 'socket error! timeout' | |
sys.exit(1) | |
except socket.gaierror,ex: | |
print 'socket error! gaierror' | |
sys.exit(1) | |
if len(buf) < 4: | |
print 'read data error' | |
sys.exit(1) | |
#计算返回的自 1900-1-1 00:00:00 的秒数 | |
secs = ord(buf[0])*pow(256,3)+ord(buf[1])*pow(256,2)+ord(buf[2])*pow(256,1)+ord(buf[3]) | |
ts = time.gmtime(secs - 2208988800+curtz*3600) | |
#time 是从1970-1-1 00:00:00 算起的 1970-1-1 00:00:00 是秒数是 2208988800s | |
print time.strftime("%Y-%m-%d %H:%I:%S", ts) | |
print time.strftime("%Y-%m-%d %H:%I:%S") | |
#附 Time Server: | |
''''' | |
clock.psu.edu | |
ntp0.cornell.edu | |
salmon.maths.tcd.ie | |
stdtime.gov.hk | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment