9
votes

How can I get the current date, month & year online using Python? Thanks!

EDIT-By this I mean, rather than getting it from the computer's date-visit a website & get it, so it doesn't rely on the computer.

6
What do you mean by "online"? - Wayne Koorts
Is there any code you've tried that has failed? An error message perhaps>? A line in the python documentation that doesn't make sense? An example of what you're trying to do that helps to explain the use of the word "online"? We'll need additional details on the problem in order to help you. - Jarret Hardie
Please be nice to NTP servers. They are often provided as a public service, and the people running them have to put up with a lot of crap as it is. - Dave
I should point out that just-the-time.appspot.com OTOH should be game for heavy-ish load -- Google says it provides enough free resources for 5 millions pageviews/month or so (and just-the-time is definitely way more lightweight per pageview than just about any web app I can think of;-). Hmmm, let me opensource it so people can easily run their own instances... - Alex Martelli
OK, the (trivial) sources are now available at code.google.com/p/just-the-time so anybody can run their own instance, etc etc. - Alex Martelli

6 Answers

37
votes

So thinking about the "would be so trivial" part I went ahead and just made a google app engine web app -- when you visit it, it returns a simple response claiming to be HTML but actually just a string such as 2009-05-26 02:01:12 UTC\n. Any feature requests?-)

Usage example with Python's urllib 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'
5
votes

If you can't use NTP, but rather want to stick with HTTP, you could urllib.urlget("http://developer.yahooapis.com/TimeService/V1/getTime") and parse 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 final comment (the error message is due to lack of APP ID). There probably are more suitable web services to get the current date and time in HTTP (without requiring registration &c), since e.g. making such a service freely available on Google App Engine would be so trivial, but I don't know of one offhand.

2
votes

In order to utilise an online time string, e.g. derived from an online service (http://just-the-time.appspot.com/), it can be read and converted into a 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 good readable)

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

little exercise:
Comparing your own UTC time with the 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

(bear in mind that processing time is included also)

1
votes

For this NTP server can be used.

import ntplib
import datetime, time
print('Make sure you have an internet connection.')

try:

    client = ntplib.NTPClient()
    response = client.request('pool.ntp.org')
    Internet_date_and_time = datetime.datetime.fromtimestamp(response.tx_time)  
    print('\n')
    print('Internet date and time as reported by NTP server: ',Internet_date_and_time)


except OSError:

    print('\n')
    print('Internet date and time could not be reported by server.')
    print('There is not internet connection.')
    
0
votes

here is a python module for hitting NIST online http://freshmeat.net/projects/mxdatetime.

0
votes

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