Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get an accurate UTC time with Python?

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?

like image 251
tslocum Avatar asked Oct 21 '09 06:10

tslocum


People also ask

How do you generate UTC time in python?

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.

Is python time time 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.

How do I find my UTC timestamp?

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.

What is the format of UTC time?

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.


Video Answer


1 Answers

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.

like image 173
Ned Deily Avatar answered Sep 22 '22 17:09

Ned Deily