我正在创建一个python模块,该模块将输出所选NTP池服务器的时间到毫秒精度,以此作为显示服务器时间戳变化的练习。到目前为止,我已经能够将原始服务器时间戳打印到2秒钟的精度内,但是如何获得毫秒精度呢?
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))
Run Code Online (Sandbox Code Playgroud)
小智 5
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"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4424 次 |
| 最近记录: |