如何使用Python获得准确的UTC时间?
我编写了一个桌面应用程序,并使用 datetime.datetime.utcnow()
来添加时间戳,但是我最近注意到,一些使用该应用程序的人得到的结果与我们在以下位置运行该程序时得到的结果大不相同:同时。有没有办法在本地获取 UTC 时间而不使用 urllib 从网站获取它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Python 依赖于底层操作系统来提供准确的时钟。如果它不这样做,你除了绕过操作系统之外别无选择。 此处提供了 NTP 客户端的纯 Python 实现。一种非常简单的方法:
但是,持续访问其他 NTP 服务器并不是很好。一个好的网络公民会使用 ntp 客户端库来跟踪操作系统时钟与从服务器获取的时钟之间的偏移,并且仅定期轮询来调整时间。
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:
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.
实际上,ntplib 会计算往返延迟的偏移量。
它可以通过 NTP 响应的“偏移”属性获得。因此结果应该不会很疯狂。
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.