Python Internet Date?

How can I get the current date, month and year on the Internet using Python? Thanks!

EDIT. I mean, instead of getting it from the date of the computer - visit the website and get it, so it does not rely on the computer.

+4
source share
5 answers

So, thinking about the “such trivial” part, I went ahead and just made a web application with the Google engine - when you visit it, it returns a simple answer that claims to be HTML, but really just a string like 2009-05-26 02:01:12 UTC\n . Any feature requests? -)

Example usage with the urllib Python module:

Python 2.7

 >>> from urllib2 import urlopen >>> res = urlopen('http://just-the-time.appspot.com/') >>> time_str = res.read().strip() >>> time_str '2017-07-28 04:55:48' 

Python 3.x +

 >>> from urllib.request import urlopen >>> res = urlopen('http://just-the-time.appspot.com/') >>> result = res.read().strip() >>> result b'2017-07-28 04:53:46' >>> result_str = result.decode('utf-8') >>> result_str '2017-07-28 04:53:46' 
+27
source

If you cannot use NTP but want to use HTTP, you can urllib.urlget("http://developer.yahooapis.com/TimeService/V1/getTime") and analyze the results:

 <?xml version="1.0" encoding="UTF-8"?> <Error xmlns="urn:yahoo:api"> The following errors were detected: <Message>Appid missing or other error </Message> </Error> <!-- p6.ydn.sp1.yahoo.com uncompressed/chunked Mon May 25 18:42:11 PDT 2009 --> 

Note that the datetime (in PDT) is in the last comment (error message due to missing APP identifier). There are probably more suitable web services for getting the current date and time in HTTP (without the need to register and with), since, for example, providing such a service available in the Google App Engine would be so trivial, but I don’t know about one of them.

+4
source

here is the python module for accessing NIST online http://freshmeat.net/projects/mxdatetime .

0
source

Perhaps you mean the NTP protocol? This project can help: http://pypi.python.org/pypi/ntplib/0.1.3

0
source

To use an online time string, for example, obtained from an online service ( http://just-the-time.appspot.com/ ), it can be read and converted to datetime.datetime format using urllib2 and datetime.datetime:

 import urllib2 from datetime import datetime def getOnlineUTCTime(): webpage = urllib2.urlopen("http://just-the-time.appspot.com/") internettime = webpage.read() OnlineUTCTime = datetime.strptime(internettime.strip(), '%Y-%m-%d %H:%M:%S') return OnlineUTCTime 

or very compact (less readable)

 OnlineUTCTime=datetime.strptime(urllib2.urlopen("http://just-the-time.appspot.com/").read().strip(), '%Y-%m-%d %H:%M:%S') 

little exercise:
Comparing your UTC time with online time:

 print(datetime.utcnow() - getOnlineUTCTime()) # 0:00:00.118403 #if the difference is negatieve the result will be something like: -1 day, 23:59:59.033398 

(remember that processing time is also included)

0
source

All Articles