Solihull
Solihull

Reputation:

Python Getting date online?

How can I get the current date, month & year online using Python? By this I mean, rather than getting it from the computer's date-visit a website and get it, so it doesn't rely on the computer.

Upvotes: 13

Views: 19057

Answers (9)

Sarmed Wahab
Sarmed Wahab

Reputation: 21

Here is the code I made for myself. I was getting a problem in linux that the date and time changes each time I switch on my PC, so instead setting again and again as the internet requires proper date. I made this script which will be used by date command to set date and time automatically through an alias.

    import requests

    resp = requests.get('https://www.timeapi.io/api/Time/current/zone?timeZone=etc/utc')
    resp = resp.text
    resp = str(resp)
    resp
    first = resp.find('"date":"')  + 8
    rp = ''
    for i in range(first , 145):
        rp = resp[i] + rp
    print(rp[::-1]+"\n")
    second = resp.find('"time":"')  + 8

    rp_2 = ''
    for i in range(second , 160):
        rp_2 = resp[i] + rp_2
    print(rp_2[::-1]+"\n")

Upvotes: 0

Sean McCarthy
Sean McCarthy

Reputation: 5578

This works really well for me, no account required:

import requests
from datetime import datetime


def get_internet_datetime(time_zone: str = "etc/utc") -> datetime:
    """
    Get the current internet time from:
    'https://www.timeapi.io/api/Time/current/zone?timeZone=etc/utc'
    """
    timeapi_url = "https://www.timeapi.io/api/Time/current/zone"
    headers = {
        "Accept": "application/json",
    }
    params = {"timeZone": time_zone}

    dt = None
    try:
        request = requests.get(timeapi_url, headers=headers, params=params)
        r_dict = request.json()
        dt = datetime(
            year=r_dict["year"],
            month=r_dict["month"],
            day=r_dict["day"],
            hour=r_dict["hour"],
            minute=r_dict["minute"],
            second=r_dict["seconds"],
            microsecond=r_dict["milliSeconds"] * 1000,
        )
    except Exception:
        logger.exception("ERROR getting datetime from internet...")
        return None

    return dt

Upvotes: 1

Piyush gupta
Piyush gupta

Reputation: 11

Goto timezonedb.com and create an account u will receive api key on the your email and use the api key in the following code

from urllib import request
from datetime import datetime
import json


def GetTime(zone):
    ApiKey="YOUR API KEY"
    webpage=request.urlopen("http://api.timezonedb.com/v2/get-time-zone?key=" +ApiKey + "&format=json&by=zone&zone="+zone)
    internettime = json.loads(webpage.read().decode("UTF-8"))
    OnlineTime = datetime.strptime(internettime["formatted"].strip(), '%Y-%m-%d %H:%M:%S')
    return(OnlineTime)


print(GetTime("Asia/Kolkata"))   #you can pass any zone region name for ex : America/Chicago

Upvotes: 1

Ranjan Pal
Ranjan Pal

Reputation: 317

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.')
    

Upvotes: 5

Alex Martelli
Alex Martelli

Reputation: 882681

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'

Upvotes: 40

Leo
Leo

Reputation: 178

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)

Upvotes: 2

Alex Martelli
Alex Martelli

Reputation: 882681

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.

Upvotes: 5

Jarret Hardie
Jarret Hardie

Reputation: 98052

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

Upvotes: 0

Zaffiro
Zaffiro

Reputation: 4934

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

Upvotes: 0

Related Questions