gpt4 book ai didi

python - 如何使用 Python ntplib 将 ntp 服务器时间精确到毫秒?

转载 作者:太空狗 更新时间:2023-10-30 02:44:01 28 4
gpt4 key购买 nike

我正在创建一个 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))

最佳答案

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"))

关于python - 如何使用 Python ntplib 将 ntp 服务器时间精确到毫秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31255633/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com