views:

427

answers:

2

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?

+5  A: 

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)

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.

Ned Deily
And with monkeypatching, you could record that offset, and change the datetime library method to apply the offset whenever some part of the application asks for the time. It would be nice if the time and datetime library would handle this kind of offset automatically. You could tell it that you want real world time, it would hit an NTP server, record the offset, and apply it every time that time is used.
Michael Dillon
This doesn't account for "round-trip-time" of making the request. What you want to do is use `time.clock()` to measure how long `NTPClient()` took to respond, split that in half and add that to the given time. That's accurate.
S.Lott
+1  A: 

Actually, ntplib computes this offset accounting for round-trip delay. It's available through the "offset" attribute of the NTP response. Cheers

neologix