Python NTP library (ntplib) offers a simple interface to query NTP servers from Python. But it does not support IPv6 NTP servers. I wrote a patch for ntplib to support IPv6 connections. You can download the patch file here and the patched library here.
The code bellow is a simple IPv6 enabled NTP client (ntpdate.py) in Python for Windows, using the patched ntplib. It doesn't (and won't) support Linux because the official NTP release offers IPv6 support on that platform.
#!/usr/bin/env python
# ntpdate.py - set the date and time via NTP
# An IPv6 enabled ntp client, for Windows ONLY.import ntplib, time
from os import system
from sys import argvdef usage():
print '''Usage: ntpdate.py [-qh] server
Example:
ntpdate.py 210.72.145.44 # IPv4
ntpdate.py ntp6.remco.org # IPv6
Options:-q Query only - don't set the clock.
-h Print this message.IPv6 NTP Server List:
ntp6.remco.org [2001:888:1031::2]
ntp6.space.net [2001:608:0:dff::2]
time.buptnet.edu.cn [2001:da8:202:10::60]
time.join.uni-muenster.de [2001:638:500:717:2e0:4bff:fe04:bc5f]
ntp.sixxs.net [2001:1291:2::b]
ntp.eu.sixxs.net [2001:808::66]
ntp.us.sixxs.net [2001:1291:2::b]
ntp.rhrk.uni-kl.de [2001:638:208:9::116]
ntp.ipv6.uni-leipzig.de [2001:638:902:1::10]
ntp.hexago.com [2001:5c0:0:2::25]
ntp1.bit.nl [2001:7b8:3:2c::123]Report bugs to http://solrex.org.'''
sys.exit()def main():
ntp_svr = ''
query = Falsefor a in argv[1:]:
if a == '-q':
query = True
elif a == '-h':
usage()
else:
ntp_svr = a
if ntp_svr == '':
usage()c = ntplib.NTPClient()
res = c.request(ntp_svr, version=3)
t_epoch = res.offset + res.delay + time.time()
t = time.localtime(t_epoch)
centi_sec = t_epoch%1 * 100
time_str = time.strftime('%H:%M:%S', t)
if not query:
system('time %s.%2.0f' % (time_str, centi_sec))
date_str = time.strftime('%Y-%m-%d', t)
system('date %s' % date_str)
if query:
print 'server %s, stratum %d, offset %f, delay %f' % (
ntp_svr, res.stratum, res.offset, res.delay)
print '%s %s ntpdate.py: time server %s offset %f sec' % (
time.strftime('%d %b', t), time_str, ntp_svr, res.offset)if __name__ == '__main__':
main()
这个应该比上一篇那个精确多了,考虑用一下~