flask app return time as json in python

You can use the datetime library to get the current time and the jsonify function from the flask module to return the time as JSON.

Here's an example code:

main.py
from flask import Flask, jsonify
from datetime import datetime

app = Flask(__name__)

@app.route('/time')
def get_time():
    time = datetime.now()
    formatted_time = time.strftime("%H:%M:%S")
    return jsonify({'time': formatted_time})

if __name__ == '__main__':
    app.run()
283 chars
14 lines

In this example, a new route named /time is defined. When a GET request is made to this route, it calls the get_time function. This function gets the current time using the datetime.now() function, formats the time to a string using strftime, and returns a JSON object with the formatted time.

To test this code, start your Flask application and go to http://localhost:5000/time in your web browser. You should see something like this:

main.py
{"time": "14:30:00"}
21 chars
2 lines

related categories

gistlibby LogSnag