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?
Getting the UTC timestampUse the datetime. datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC.
Python time time() Method Pythom time method time() returns the time as a floating point number expressed in seconds since the epoch, in UTC.
Use the getTime() method to get a UTC timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation. Calling the method from any time zone returns the same UTC timestamp.
Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"). Times are expressed in local time, together with a time zone offset in hours and minutes. A time zone offset of "+hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes ahead of UTC.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With