如何使用 Python 获得准确的 UTC 时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1599060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:39:58  来源:igfitidea点击:

How can I get an accurate UTC time with Python?

pythondatetimetimestamputc

提问by tslocum

I wrote a desktop application and was using datetime.datetime.utcnow()for timestamping, however I've recently noticed that some people using the application get wildly different results than I do when we run the program at the same time. Is there any way to get the UTC time locally without using urllib to fetch it from a website?

我编写了一个桌面应用程序并datetime.datetime.utcnow()用于时间戳,但是我最近注意到有些人使用该应用程序得到的结果与我们同时运行该程序时得到的结果截然不同。有没有办法在不使用 urllib 从网站上获取它的情况下在本地获取 UTC 时间?

回答by Ned Deily

Python depends on the underlying operating system to provide an accurate time-of-day clock. If it isn't doing that, you don't have much choice other than to bypass the o/s. There's a pure-Python implementation of an NTP client here. A very simple-minded approach:

Python 依赖于底层操作系统来提供准确的时钟。如果它不这样做,除了绕过 o/s 之外,您别无选择。有一个纯Python实现NTP客户端的位置。一个非常简单的方法:

>>> import ntplib,datetime
>>> x = ntplib.NTPClient()
>>> datetime.datetime.utcfromtimestamp(x.request('europe.pool.ntp.org').tx_time)
datetime.datetime(2009, 10, 21, 7, 1, 54, 716657)

However, it would not be very nice to be continually hitting on other NTP servers out there. A good net citizen would use the ntp client library to keep track of the offset between the o/s system clock and that obtained from the server and only periodically poll to adjust the time.

但是,不断地访问其他 NTP 服务器并不是很好。一个好的网民会使用 ntp 客户端库来跟踪 o/s 系统时钟与从服务器获得的时钟之间的偏移,并且只定期轮询以调整时间。

回答by neologix

Actually, ntplib computes this offset accounting for round-trip delay. It's available through the "offset" attribute of the NTP response. Therefore the result should not very wildly.

实际上,ntplib 计算了往返延迟的偏移量。它可以通过 NTP 响应的“偏移”属性获得。因此结果应该不会很疯狂。