繁体   English   中英

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

[英]How to get time from an NTP server?

我需要从 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 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())

作为对 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 库

以下函数使用 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")

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM