所以我需要从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))
答案 0 :(得分:2)
作为对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/
答案 1 :(得分:1)
这将起作用
python3
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 = '\x1b' + 47 * '\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())
答案 2 :(得分:0)
以下功能在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")
答案 3 :(得分:0)
这基本上是Ahmads的答案,但是在Python 3上为我工作。我目前热衷于Arrow,因为它简化了时间,然后您得到:
import arrow
import socket
import struct
import sys
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 arrow.get(t)
print(RequestTimefromNtp())