0

I have an assignment to construct a simple webpage with flask. I've gotten it working and have everything I need so far in my templates. What I can't figure out is how to display the date time on my pages. Do I put the date time in the templates individually, or put it in the base python code? My instructions say to just use the standard python date time function. But it isn't displaying when i test my page.

from flask import Flask
from flask import render_template
import datetime

app = Flask(__name__)

@app.route('/')
def index():
    return show_home()


def show_home():
    return render_template('index.html')

@app.route('/ingredients/')
def ingredients():
    return show_ingredients()

def show_ingredients():
    return render_template('ingredients.html')

@app.route('/cooking_instructions/')
def cook_it():
    return show_cook_it()

def show_cook_it():
    return render_template('cooking_instructions.html')
1
  • I don't even see you using the datetime module anywhere in your program. You need to use datetime.now() and display it in one of your templates. Commented Dec 2, 2020 at 3:02

1 Answer 1

3

You can just pass the string representation of the datetime into the render_template function like so:

from datetime import datetime

@app.route('/example')
def example():
    return render_template('template.html', datetime = str(datetime.now()))

You can then access the variable in your template using the syntax {{ datetime }}. Of course you can customize how your datetime will look in your template by using the strftime method on your datetime object.

This will not be dynamic, so once the template renders the datetime will not update. If you are looking for a counting clock you need to write that code in javascript. Check out this example HTML Display Current date

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.