【问题标题】:How to ntp server time down to millisecond precision using Python ntplib?如何使用 Python ntplib 将服务器时间精确到毫秒?
【发布时间】:2019-12-18 22:00:50
【问题描述】:

我正在创建一个 python 模块,它将从选择的 NTP 池服务器输出时间到毫秒精度,作为展示服务器时间戳如何变化的练习。到目前为止,我已经能够将原始服务器时间戳打印到一秒精度内,但我怎样才能获得毫秒精度?

ntp_pool = '0.pool.ntp.org', \
       'uk.pool.ntp.org', \
       'ie.pool.ntp.org'

def get_ntp_time():
    for item in ntp_pool:
        call = ntplib.NTPClient()
        response = call.request(item, version=3)
        print(time.ctime(response.orig_time))

【问题讨论】:

标签: python ntp


【解决方案1】:

for 循环可能会为您的结果着色,因为每次迭代都有时间流逝。

无论如何,ntp 响应是一个具有微秒精度的时间戳,所以限制似乎在time.ctime 之内,只能降到秒精度

您可以改用datetime.fromtimestamp,也可以选择使用strftime 使其更漂亮。我的示例半心半意地模仿了现有代码的输出。

from datetime import datetime

def get_ntp_time():
for item in ntp_pool:
    call = ntplib.NTPClient()
    response = call.request(item, version=3)
    t = datetime.fromtimestamp(response.orig_time)
    print(t.strftime("%a %b %d %H:%M:%S.%f"))

【讨论】:

    【解决方案2】:

    我认为这里有些误导:response.orig_time 是发出请求的客户端的时间,而不是服务器的时间。请参阅IETF RFC5905,第 23 页:“原始时间戳 (org):请求离开服务器时客户端的时间 [...]”。代码的最新版本应该类似于

    import ntplib
    from datetime import datetime, timezone
    
    NTP_SERVERS = ['0.pool.ntp.org', 'uk.pool.ntp.org']
    
    for server in NTP_SERVERS:
        client = ntplib.NTPClient()
        response = client.request(server, version=3)
        print(f"server: {server}")
        print(f"client time of request: {datetime.fromtimestamp(response.orig_time, timezone.utc)}")
        print(f"server responded with: {datetime.fromtimestamp(response.tx_time, timezone.utc)}")
    

    ...会给我例如

    server: 0.pool.ntp.org
    client time of request: 2019-12-18 13:58:52.224058+00:00
    server responded with: 2019-12-18 13:58:51.289734+00:00
    server: uk.pool.ntp.org
    client time of request: 2019-12-18 13:58:52.314615+00:00
    server responded with: 2019-12-18 13:58:51.377655+00:00
    

    请注意,根据信号必须传播的距离,如果您以毫秒为单位,往返延迟 (response.delay) 可能很重要。

    【讨论】:

    • 当我运行这个客户端时间总是在服务器时间之后
    • @ibrust:这是可能的,是的。发出请求不会同步时钟。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    相关资源
    最近更新 更多