如何使用Python获得准确的UTC时间? [英] How can I get an accurate UTC time with Python?

查看:318
本文介绍了如何使用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?

推荐答案

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

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:

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

然而,不断地在其他NTP服务器上点击并不是很好。一个好的网络公民将使用ntp客户端库跟踪o / s系统时钟与从服务器获得的时钟之间的偏移量,并且仅定期轮询调整时间。

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.

这篇关于如何使用Python获得准确的UTC时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆