Readtime is one of the best features that can add quality to any blog. It gives readers a sense of how much longer this article could be. So I decided to write about how you can calculate the readtime of an article or blog in Django or a string in python.

To add readtime, import readtime and pass it some text, HTML, and markdown to get back the time it takes to read. It calculates the time some text takes the average human to read, based on Medium's read time formula.

Let's begin with the installation of the readtime library.

How to install readtime library

You can install it with the command below.

sudo pip install readtime

However, I would suggest you install this in a virtual environment to avoid any version-related issues. You can follow this guide on installing a virtual environment on windows, mac, and Linux. Once it is properly installed we can move ahead on how to use it.

Usage: readtime library

How to calculate the read time of a text:

import readtime
result = readtime.of_text('The shortest blog post in the world!')
result.seconds
2
result.text
u'1 min'

How to calculate read time of Markdown:

import readtime
readtime.of_markdown('This is **Markdown**')
1 min read

How to calculate read time of HTML:

import readtime
readtime.of_html('This is <strong>HTML</strong>')
1 min read

How to customize the Words per Minute (WPM):

WPM by default is 265

import readtime
result = readtime.of_text('The shortest blog post in the world!', wpm=5)
result.seconds
96
result.text
u'2 min'
result.wpm
5

How to integrate readtime in Django templates

To integrate readtime in Django templates, you have to create a custom template tag that takes HTML as input and returns readtime. You can check this guide about how to create custom template tags and filters in Django if you want to learn more about creating custom tags and filters.

First, you have to: - Create a folder templatetags inside your Django app. - Create init.py file inside templatetags folder. - Create an article_utils.py file inside templatetags folder.

article_utils-min

Next, you have to create a function (also called a tag) inside article_utils.py file that will take HTML as input and return time as output.

from django import template
import readtime

register = template.Library()

def read(html):
    return readtime.of_html(html)

register.filter('readtime',read)

Now in your django template (yourfile.html) wherever you want to show readtime, load the template tag we just created like this.

{% load article_utils % }

Now use the function you registered, anywhere in your template where you want to show readtime.

{{post.body|readtime}}

post is my model object and body is the field where I have stored raw HTML.

That's it. Now you can see the readtime just like this.

readtime-final-min