get time from a api in python

To get the time from an API, you can use the datetime and requests library. Here is an example:

main.py
import requests
import datetime

response = requests.get('http://worldclockapi.com/api/json/utc/now')

if response.status_code == 200:
    data = response.json()
    date_str = data['currentDateTime']
    date = datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%fZ')
    print('The current time is:', date.time())
else:
    print('Failed to get response from the API')
376 chars
13 lines

In this example, I am using the World Clock API to get the current time in UTC. The response.json() method returns the API response as a dictionary, which I use to extract the current date and time string. This string is then converted to a datetime object using the strptime() method. Finally, we extract the time from this datetime object using the time() method.

Note that the API response format may differ depending on the API you are using, so you may need to adjust the code accordingly.

related categories

gistlibby LogSnag