我需要从 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))
Run Code Online (Sandbox Code Playgroud)
小智 9
这将起作用(Python 3):
import socket
import struct
import sys
import time
def RequestTimefromNtp(addr='0.de.pool.ntp.org'):
REF_TIME_1970 = 2208988800 # Reference time
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = b'\x1b' + 47 * b'\0'
client.sendto(data, (addr, 123))
data, address = client.recvfrom(1024)
if data:
t = struct.unpack('!12I', data)[10]
t -= REF_TIME_1970
return time.ctime(t), t
if __name__ == "__main__":
print(RequestTimefromNtp())
Run Code Online (Sandbox Code Playgroud)
小智 6
作为对 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
print (datetime.fromtimestamp(response.tx_time, timezone.utc))
Run Code Online (Sandbox Code Playgroud)
此处使用的 UTC 时区。要使用不同的时区,您可以使用pytz 库