Bootstrap FreeKB - Flask - Date and Time
Flask - Date and Time

Updated:   |  Flask articles

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

Let's say your Flask app has a structure like this.

├── main.py
├── database (directory)
│   ├── example.db
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── results.html
│   └── static (directory)
│       └── custom.css

 

In your view (views.py in this example), you can use from datetime import datetime and then use context_processor to make "now" available as a variable in your HTML template files.

Check out my article on Python Date and Time for more details and examples on the datetime module.

from flask import Blueprint, render_template, request, redirect, flash, url_for
from datetime import datetime

views = Blueprint('views', __name__)

@views.context_processor
def inject_now():
    return {'now': datetime.utcnow()}

 

Then in your HTML files, you can use the "now" variable.

<p>The current year is {{ now.year }}</p>

 

For example, here is a web site that I made in Flask, where the top nav has the current year.




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 074524 in the box below so that we can be sure you are a human.