Countdown

Apr 12, 2021 |  Author: Nic La |  Tags:  project   code  

Countdown is a simple web-based countdown timer. Date to countdown to is entered in the Django admin portal using format YYYY-MM-DD hh:mm:ss. Two messages are available: start message and end message. Start message displays during countdown. End message displays after countdown is finished.

I know someone retiring soon and I wanted to make them a website that counts down to their retirement. At first, I thought I could do this entirely in Python and Django. Problem is, anything animated on a webpage is going to be made using JavaScript. It just doesn't exist elsewhere. Step 1, learn JavaScript.

I've zero experience with JavaScript but Django makes it easy to incorporate. JavaScript is treated like any other static file. Just be sure to update the header of your base.html with the call to your static file.

static folder

The magic that brings the countdown to life is JavaScript, CSS, and HTML all working together. This stackoverflow post has all three! The variable deadline is assigned the difference between now and the milliseconds to the countdown date.

var deadline = new Date(new Date().getTime() + 33 * 24 * 60 * 60 * 1000);

How do we seed the deadline variable with the milliseconds to the countdown date? Python of course! The below function takes the date in format YYYY-MM-DD hh:mm:ss and returns the total number of seconds until that date. Calling this in your view.py will ensure an up-to-date deadline each time the webpage is loaded.

def date_to_sec(date_str):
    """Takes input date and returns number of seconds until date"""
    format_str = "%Y-%m-%d %H:%M:%S"
    try:
        duedate = datetime.strptime(date_str, format_str)
    except ValueError:
        duedate = datetime.strptime("2021-04-30 17:00:00", format_str)

    # Create aware datetime instance to account for time zone and daylight saving time
    duedate = duedate.replace(tzinfo=tz.gettz("America/Los_Angeles"))
    countdown = duedate - datetime.now(tz=tz.tzlocal())

    # Don't return negative
    if int(countdown.total_seconds()) > 0:
        return int(countdown.total_seconds())
    return 0

Season with CSS according to taste. I was inspired by the Mac Countdown Screensaver.

The complete code for this project can be found on GitHub. Project in action can be found on Heroku.


Leave a comment: