Skip to content
Advertisement

Convert Date in JavaScript (from a Python Dataset)

How do I edit the date format that gets returned from a dataset from Python via a Flask App in Javascript?

It currently shows up as datetime, but I want it to show up as a custom date format.

The best type of answer would help me to understand how to access those date values and create a custom date, such as ‘Monday, 6 June 2022’. But if you can just turn it into a date, without the time, that may also suffice.

enter image description here

Python

import pandas as pd
from flask import Flask, render_template, jsonify, render_template_string, request, flash
import json
import datetime
from datetime import datetime

app = Flask(__name__)
app.secret_key = "test"

test_df = pd.DataFrame([
    ['Afghanistan', 'Report #1', 'Category #1', '2021-01-01', 'https://www.google.com', 'https://reliefweb.int/sites/default/files/styles/thumbnail/public/previews/c5/2d/c52de4ba-42d8-4383-8310-eb1a6966e803.png'],
    ['Bangladesh', 'Report #2', 'Category #1', '2021-01-01', 'https://www.google.com', 'https://reliefweb.int/sites/default/files/styles/thumbnail/public/previews/c5/2d/c52de4ba-42d8-4383-8310-eb1a6966e803.png'],
    ['Cambodia', 'Report #3', 'Category #2', '2021-01-01', 'https://www.google.com', 'https://reliefweb.int/sites/default/files/styles/thumbnail/public/previews/c5/2d/c52de4ba-42d8-4383-8310-eb1a6966e803.png']],
    columns=['Country', 'Title', 'Category', 'Date', 'Link', 'Image'])
test_df['Date'] = pd.to_datetime(test_df['Date'])
test_df = test_df.fillna("")
test_df = test_df.values.tolist()

@app.route("/hello")
def index():
    return render_template("index.html", test_df=test_df)


if __name__ == '__main__':
    app.run(debug=True, port=4000)

HTML/JavaScript

<body>

    <div class="main">
        <table class="table mydatatable" id="mydatatable">
            <thead>
                <tr>
                    <th> </th>
                    <th> </th>
                </tr>
            </thead>
            <tbody id="myTable">
            </tbody>
        </table>
    </div>


    <script>
        // Build Table
        function buildTable(data) {
            var table = document.getElementById('myTable')
            table.innerHTML = data.map(function (row) {
                let [Country, Title, Category, Date, Link, Image] = row;
                return `<tr>
                <td><br><br>
                <a href="${Link}" target='_blank'>
                    <img class="tableThumbnail" src=${Image}><br><br></td></a>
                <td>
                    <span class="tableTitle"><br><br><a href="${Link}" target='_blank'>${Title}</a><br></span>
                    <span class="tableCountry"><span>&nbsp;&nbsp;${Country}&nbsp;&nbsp;</span></span>&nbsp;&nbsp;
                    <span class="tableCategory">&nbsp;&nbsp;${Category}&nbsp;&nbsp;</span>
                    <span class="tableDate"><span><br>&nbsp;&nbsp;<i class="far fa-calendar"></i>&nbsp;&nbsp;${Date}</span></span>
                </td>
            </tr>`;
            }).join('');
        }

       const evidenceData = JSON.parse('{{ test_df|tojson }}');

        buildTable(evidenceData)

    </script>
</body>

If you’re wondering about why the values are nested like this, there’s some custom CSS styling (not included here) to make them look better.

Libraries

<!-- Jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<!-- Datatables -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>

<!-- Icons -->
<script src="https://kit.fontawesome.com/f3135b3376.js" crossorigin="anonymous"></script>

Advertisement

Answer

I recommend using the MomentJS library to change the format of the date.
Just include the library in the header.

<!-- MomentJS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>

Then you can change the date by choosing the format.

moment(date).format('dddd, D MMMM YYYY');

As a little tip, I advise you to choose your variable names in such a way that they do not collide with predefined names in the language. In JavaScript, the CamelCase notation is used as the standard.

let [country, title, category, date, link, image] = row;
date = moment(date).format('dddd, D MMMM YYYY');
// ... 

A variant with Date.prototype.toLocaleDateString() is this.

let opts = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
let ds = new Date('2021-01-01').toLocaleDateString('en-US', opts);
console.log(ds);

The output should look like this.

Friday, January 1, 2021
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement