如何从 NTP 服务器获取时间?

问题描述 投票:0回答:6

我需要从 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))
python ntp
6个回答
10
投票

这会起作用(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())

8
投票

调用 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))

这里使用UTC时区。要处理不同的时区,您可以使用 pytz library


2
投票

这基本上是 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())

1
投票

以下函数使用 python 3 运行良好:

def GetNTPDateTime(server):
    try:
        ntpDate = None
        client = ntplib.NTPClient()
        response = client.request(server, version=3)
        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")


-1
投票

I used ntplib server and get date and change format in dd-mm-yyyy

© www.soinside.com 2019 - 2024. All rights reserved.