Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current date time in python flask

I need to display the date and time on the browser through a variable.I am just beginner of python and flask. Here is my code. Please suggest an idea or two to point me in the right direction.

from datetime import datetime
date = datetime.now()

from flask import Flask


app = Flask(__name__)

@app.route("/")
def home():
    return date

if __name__ == "__main__":
    app.run(debug=True)

But it shows "internal server error"

like image 755
ping pong Avatar asked Jan 26 '26 00:01

ping pong


1 Answers

You must put the date declaration inside your route:

from datetime import datetime

from flask import Flask
    
app = Flask(__name__)

@app.route("/")
def home():
    date = datetime.now()
    return str(date)

if __name__ == "__main__":
    app.run(debug=True)

If you want the date in a more presentative format replace:

return str(date)

by:

return date.strftime("%d/%m/%y")

as others suggested in the comments

like image 97
IoaTzimas Avatar answered Jan 28 '26 13:01

IoaTzimas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!