how to get time from an api in python

You can get time from an API by sending a request to the endpoint that returns time data in a specified format. Here's an example code snippet that uses the datetime library and the requests library to get time from an API:

main.py
import requests
from datetime import datetime

# API endpoint that returns time data in a JSON format
url = 'http://worldclockapi.com/api/json/utc/now'

response = requests.get(url).json()

# extract time from the response
time_str = response['currentDateTime']

# create datetime object from the time string
dt_obj = datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%S.%fZ')

print(dt_obj.time()) # print the time portion of the datetime object
441 chars
16 lines

The above code uses the worldclockapi.com API to get current UTC time, extracts the time string from the API response, and converts it into a datetime object. Finally, it prints only the time portion of the datetime object. Note that you need to have requests library installed to run the code.

related categories

gistlibby LogSnag