所以我需要从NTP服务器获得英国的时间。在网上找到了东西,但是当我试用代码的时候,我总是得到一个返回日期时间,就像我的电脑一样。我改变了计算机上的时间,确认了这一点,我总是这样做,所以它不是来自NTP服务器。代码如下,任何帮助表示赞赏
import ntplib
from time import ctime
c = ntplib.NTPClient()
response = c.request('uk.pool.ntp.org', version=3)
response.offset
print (ctime(response.tx_time))
print (ntplib.ref_id_to_text(response.ref_id))
x = ntplib.NTPClient()
print ((x.request('ch.pool.ntp.org').tx_time))
作为对NTP服务器的调用返回的时间戳以秒为单位返回时间。默认情况下,ctime()根据本地计算机的时区设置提供日期时间格式。因此,对于英国时区,您需要使用该时区转换tx_time。 python的内置datetime模块包含用于此目的的功能
import ntplib
from datetime import datetime, timezone
c = ntplib.NTPClient()
# Provide the respective ntp server ip in below function
response = c.request('uk.pool.ntp.org', version=3)
response.offset
# UTC timezone used here, for working with different timezones you can use [pytz library][1]
print (datetime.fromtimestamp(response.tx_time, timezone.utc))
[1]: http://pytz.sourceforge.net/
以下函数使用python 3运行良好:
def GetNTPDateTime(server):
try:
ntpDate = None
client = ntplib.NTPClient()
response = client.request(server, version=3)
response.offset
ntpDate = ctime(response.tx_time)
print (ntpDate)
except Exception as e:
print (e)
return datetime.datetime.strptime(ntpDate, "%a %b %d %H:%M:%S %Y")