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 controller (__init__.py) 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 Flask


def app():
    app = Flask(__name__,
                static_url_path='', 
                static_folder='static/',
                template_folder='templates/')
     

    from . import views
    app.register_blueprint(views.blueprint, url_prefix='/')

    @app.context_processor
    def inject_now():
        from datetime import datetime
        return {'now': datetime.utcnow()}    

    db.init_app(app)    


    return app

 

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 4f69c2 in the box below so that we can be sure you are a human.