Django - Show list datetime values in template - django

I have below code which outputs datetime values as shown below:
available_hours = [hour for hour in hours_between if hour not in reserved_times]
print(available_hours)
[datetime.datetime(2021, 12, 8, 12, 0), datetime.datetime(2021, 12, 8, 13, 0), datetime.datetime(2021, 12, 8, 14, 0), datetime.datetime(2021, 12, 8, 16, 0), datetime.datetime(2021, 12, 8, 17, 0), datetime.datetime(2021, 12, 8, 18, 0), datetime.datetime(2021, 12, 8, 19, 0), datetime.datetime(2021, 12, 8, 20, 0), datetime.datetime(2021, 12, 8, 21, 0)]
I render them in the template like:
{{ available_hours }}
and i got all above datetime values.
How can i change the format so i can show them like Mon 12 2021, 21:00?
Thank you

try this
<p>
available hours:
{% for my_time in available_hours %}
{{ my_time|date:"M d Y, H:i" }}
{% endfor %}
</p>

Related

Initialising ChartJS with dataset index[0]

I've written a python script to get data from Google Search Console, stores it etc etc and print out an html output. The whole thing works really well and I've used buttons to select different datasets to hide/show them as you click on them.
I have no idea how to initialise the chart with index[0] though, all datasets are being rendered and shown when the page is loaded. I've had a look through the documentation but this is way over my head. Is there something in the options I can call to just show one dataset right from the start?
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="m-5">
<div class="card col-md-6 offset-md-3">
<canvas id="myChart" ></canvas>
</div>
</div>
<div class="listSelector">
<ul>
<button onclick="toggleData(0)">https://www.somewebsite.co.uk/</button><br>
<button onclick="toggleData(1)">https://www.somewebsite.co.uk/blog/</button><br>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js"></script><script>const ctx = document.getElementById('myChart').getContext('2d');const myChart = new Chart(ctx,
{type:"line",data:{labels:['2022-07-16', '2022-07-17', '2022-07-18', '2022-07-19', '2022-07-20', '2022-07-21', '2022-07-22', '2022-07-23', '2022-07-24', '2022-07-25', '2022-07-26', '2022-07-27', '2022-07-28', '2022-07-29', '2022-07-30', '2022-07-31', '2022-08-01', '2022-08-02', '2022-08-03', '2022-08-04', '2022-08-05', '2022-08-06', '2022-08-07', '2022-08-08', '2022-08-09', '2022-08-10', '2022-08-11', '2022-08-12', '2022-08-13', '2022-08-14', '2022-08-15', '2022-08-16', '2022-08-17', '2022-08-18', '2022-08-19', '2022-08-20', '2022-08-21', '2022-08-22', '2022-08-23', '2022-08-24', '2022-08-25', '2022-08-26', '2022-08-27', '2022-08-28', '2022-08-29', '2022-08-30', '2022-08-31', '2022-09-01', '2022-09-02', '2022-09-03', '2022-09-04', '2022-09-05', '2022-09-06', '2022-09-07', '2022-09-08', '2022-09-09', '2022-09-10', '2022-09-11', '2022-09-12', '2022-09-13', '2022-09-14', '2022-09-15', '2022-09-16', '2022-09-17', '2022-09-18', '2022-09-19', '2022-09-20', '2022-09-21', '2022-09-22', '2022-09-23', '2022-09-24', '2022-09-25', '2022-09-26', '2022-09-27', '2022-09-28', '2022-09-29', '2022-09-30', '2022-10-01', '2022-10-02', '2022-10-03', '2022-10-04', '2022-10-05', '2022-10-06', '2022-10-07', '2022-10-08', '2022-10-09', '2022-10-10', '2022-10-11', '2022-10-12', '2022-10-13', '2022-10-14', '2022-10-15', '2022-10-16', '2022-10-17', '2022-10-18', '2022-10-19', '2022-10-20', '2022-10-21', '2022-10-22', '2022-10-23'],datasets: [
{label: "https://www.somewebsite.co.uk/", data: [4551, 5072, 5426, 5224, 4672, 4257, 4035, 4376, 4680, 4916, 4957, 4929, 4786, 5391, 5390, 5991, 5463, 5308, 4739, 4450, 4577, 4831, 5045, 5006, 4609, 4098, 3720, 4300, 5185, 5251, 4503, 3757, 3971, 3967, 3772, 3619, 3585, 3601, 3485, 3454, 3497, 3431, 3602, 3732, 4574, 4470, 4393, 3541, 3397, 3458, 3564, 3823, 3897, 3682, 3158, 3081, 3395, 4089, 4502, 4664, 4866, 4398, 4098, 3845, 4018, 4149, 4272, 4324, 4285, 4085, 4403, 4754, 5957, 6702, 7324, 7109, 7209, 7477, 7800, 7785, 7639, 7195, 6739, 6729, 7143, 7481, 7313, 6630, 6127, 5847, 6239, 6811, 7285, 7335, 7139, 6941, 6663, 6233, 4054, 1937],fill: "start", backgroundColor: ['rgba(90, 204, 204,0.4)'], borderColor: ['rgba(90, 204, 204, 1)'], borderWidth: 2 },
{label: "https://www.somewebsite.co.uk/blog/", data: [75, 88, 123, 116, 92, 62, 39, 59, 87, 90, 83, 55, 53, 37, 51, 77, 99, 83, 61, 41, 32, 30, 35, 35, 34, 28, 30, 21, 20, 17, 32, 40, 43, 38, 29, 33, 33, 47, 56, 49, 34, 17, 14, 19, 23, 31, 25, 17, 7, 17, 28, 39, 57, 55, 47, 21, 20, 22, 20, 22, 26, 29, 22, 21, 26, 48, 62, 63, 47, 35, 33, 33, 30, 32, 36, 37, 29, 27, 21, 22, 21, 24, 33, 25, 37, 35, 44, 34, 29, 20, 13, 23, 44, 52, 42, 32, 32, 27, 13, 2],fill: "start", backgroundColor: ['rgba(90, 204, 204,0.4)'], borderColor: ['rgba(90, 204, 204, 1)'], borderWidth: 2 },
]},options: {
plugins: {
legend: {
display:false
}
},
scales: {
y: {
beginAtZero: true
}}}});
function toggleData(value) {
const showValue = myChart.isDatasetVisible(value)
if(showValue === true) {
myChart.hide(value);
}
if(showValue === false) {
myChart.show(value);
}
}
</script>
My script can produce hundreds of datasets, I've shortened it to 2 here because of the size of the label and data arrays.
I'm missing a function or method call. I would like the very first dataset to be shown, then as I click on different buttons the chart to refresh. I think I can do that, I'm just looking for the initialisation of the chart.

Google Charts: Why am I getting two select events when I have animation turned on

I attach a select event to charts -- a column chart and a pie chart
When I turn on animation, I get two select events for a single column select action from the column chart (but just one, correctly, from the pie chart, which doesn't animate).
For the column chart, the first event returns the correct selection data [{column:1, row:1}], but the second event returns an empty array.
With animation turned off (commented out) I get the correct response, namely only one event when a user selects a column.
Has anyone seen this? What do I do? I haven't found any value that lets me even differentiate whether the event is occurring in the presence of animation, or any other logical way to at least filter out the rogue second event. Obviously I would like to suppress the incorrect second event when animation is turned on.
Here's the animation spec:
let options = {
animation:{
startup: true,
duration: 500,
easing: 'out',
},
the 'select' event on a ColumnChart seems to be working fine with animation here,
see following working snippet...
is there more you can share?
are you creating the charts directly or using the ChartWrapper class?
which packages are you using, 'corechart'?
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('timeofday', 'Time of Day');
data.addColumn('number', 'Motivation Level');
data.addColumn('number', 'Energy Level');
data.addRows([
[{v: [8, 0, 0], f: '8 am'}, 1, .25],
[{v: [9, 0, 0], f: '9 am'}, 2, .5],
[{v: [10, 0, 0], f:'10 am'}, 3, 1],
[{v: [11, 0, 0], f: '11 am'}, 4, 2.25],
[{v: [12, 0, 0], f: '12 pm'}, 5, 2.25],
[{v: [13, 0, 0], f: '1 pm'}, 6, 3],
[{v: [14, 0, 0], f: '2 pm'}, 7, 4],
[{v: [15, 0, 0], f: '3 pm'}, 8, 5.25],
[{v: [16, 0, 0], f: '4 pm'}, 9, 7.5],
[{v: [17, 0, 0], f: '5 pm'}, 10, 10],
]);
var view = new google.visualization.DataView(data);
view.setColumns([{sourceColumn:0, type: 'string', calc: 'stringify'}, 1]);
var options = {
animation:{
startup: true,
duration: 500,
easing: 'out',
},
hAxis: {
title: 'Time of Day',
format: 'h:mm a',
viewWindow: {
min: [7, 30, 0],
max: [17, 30, 0]
}
},
isStacked: true,
title: 'Motivation and Energy Level Throughout the Day',
vAxis: {
title: 'Rating (scale of 1-10)'
}
};
var chartCol = new google.visualization.ColumnChart(document.getElementById('column_div'));
var chartPie = new google.visualization.PieChart(document.getElementById('pie_div'));
google.visualization.events.addListener(chartCol, 'select', function () {
showSelection(chartCol);
});
google.visualization.events.addListener(chartPie, 'select', function () {
showSelection(chartPie);
});
function showSelection(sender) {
document.getElementById('msg_div').innerHTML += (new Date()).getTime() + ' -- ' + JSON.stringify(sender.getSelection()) + '<br/>';
}
chartCol.draw(data, options);
chartPie.draw(view, {
legend: 'none',
theme: 'maximized'
});
},
packages: ['corechart']
});
div {
padding: 6px 6px 6px 6px;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="column_div"></div>
<div id="pie_div"></div>
<div id="msg_div"></div>

How to change selected column border color & width in Google Charts?

I am using Google Charts. I want to change border color & width of selected column. By default stroke color is white and width is 1. I want to change border color to black and width to 2.
Code :
var data = google.visualization.arrayToDataTable(mydata);
var options = {
width: 600,
height: 400,
legend: {position: 'top', maxLines: 4},
bar: {groupWidth: '50%'},
isStacked: true
};
var chart = new google.visualization.ColumnChart(document.getElementById('mydiv'));
chart.draw(data, options);
There is no build-in option to set this style, but you may ovveride these settings for stroke-color/width via CSS:
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawStacked);
function drawStacked() {
var data = new google.visualization.DataTable();
data.addColumn('timeofday', 'Time of Day');
data.addColumn('number', 'Motivation Level');
data.addColumn('number', 'Energy Level');
data.addRows([
[{v: [8, 0, 0], f: '8 am'}, 1, .25],
[{v: [9, 0, 0], f: '9 am'}, 2, .5],
[{v: [10, 0, 0], f:'10 am'}, 3, 1],
[{v: [11, 0, 0], f: '11 am'}, 4, 2.25],
[{v: [12, 0, 0], f: '12 pm'}, 5, 2.25],
[{v: [13, 0, 0], f: '1 pm'}, 6, 3],
[{v: [14, 0, 0], f: '2 pm'}, 7, 4],
[{v: [15, 0, 0], f: '3 pm'}, 8, 5.25],
[{v: [16, 0, 0], f: '4 pm'}, 9, 7.5],
[{v: [17, 0, 0], f: '5 pm'}, 10, 10],
]);
var options = {
legend: {position: 'top', maxLines: 4},
isStacked: true};
var chart = new google.visualization.ColumnChart(document.getElementById('mydiv'));
chart.draw(data, options);
}
#mydiv svg>g>g>g>g>rect[stroke="#ffffff"][stroke-width="1"] {
stroke: black !important;
stroke-width: 2px !important;
}
<div id="mydiv"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
You could set column style (border color & width) by applying Column styles on the selected column using select event as demonstrated below:
google.load("visualization", '1.1', { packages: ['corechart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Genre', 'Fantasy & Sci Fi', 'Romance', 'Mystery/Crime', 'General','Western', 'Literature'],
['2010', 10, 24, 20, 32, 18, 5],
['2020', 16, 22, 23, 30, 16, 9],
['2030', 28, 19, 29, 30, 12, 13]
]);
var options = {
width: 600,
height: 400,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '75%' },
isStacked: true,
};
var view = new google.visualization.DataView(data);
var chart = new google.visualization.ColumnChart(document.getElementById('columnchart_stacked'));
google.visualization.events.addListener(chart, 'select', function () {
highlightBar(chart,options,view);
});
chart.draw(data, options);
}
function highlightBar(chart,options,view) {
var selection = chart.getSelection();
if (selection.length) {
var row = selection[0].row;
var column = selection[0].column;
//1.insert style role column to highlight selected column
var styleRole = {
type: 'string',
role: 'style',
calc: function(dt, i) {
return (i == row) ? 'stroke-color: #000000; stroke-width: 2' : null;
}
};
var indexes = [0, 1, 2, 3, 4, 5, 6];
var styleColumn = findStyleRoleColumn(view)
if (styleColumn != -1 && column > styleColumn)
indexes.splice(column, 0, styleRole);
else
indexes.splice(column+1, 0, styleRole);
view.setColumns(indexes);
//2.redraw the chart
chart.draw(view, options);
}
}
function findStyleRoleColumn(view) {
for (var i = 0; i < view.getNumberOfColumns() ; i++) {
if (view.getColumnRole(i) == "style") {
return i;
}
}
return -1;
}
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['corechart']}]}"></script>
<div id="columnchart_stacked" style="width: 600px; height: 420px;"></div>
JSFiddle

Google Charts API - Column patterns and "TimeOfDay" data type

I'm working with the Google Charts API to create a graph of a student's test-taking performance. On the X axis, the graph shows the days of the week. On the Y axis, the graph shows how long the student spent taking the exam. (The goal is for teachers to see if the student speeds up). However, I have a problem:
My data is in the timeofday format, and I'm providing values to the chart as time durations using the Google Charts [HH,MM,SS,MSEC] format. When the chart renders, the Y axis is printed as "HH:MM:SS". I'd really like to customize that because the seconds are pretty useless and it looks messier than I'd like.
The Charts API says you can specify a "pattern" for a column, and I've specified "HH:MM". However, that doesn't seem to take effect at all. Anybody have experience formatting timeofday in Google Charts and know how to do this?
The format is buried deep in the API documentation. (http://code.google.com/apis/chart/interactive/docs/reference.html). It is about quarter way down, it says:
If the column type is 'timeofday', the value is an array of four
numbers: [hour, minute, second, milliseconds].
More than words can say: The followingURL is a full working version for Stockprices during the days, and can be found at 'http://www.harmfrielink.nl/Playgarden/GoogleCharts-Tut-07.html'
Since a complete listing can not be posted correctly I only give the important parts:
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('datetime', 'Time');
dataTable.addColumn('number', 'Price (Euro)');
dataTable.addRows([
[new Date(2014, 6, 2, 9, 0, 0, 0), 21.40],
[new Date(2014, 6, 2, 11, 0, 0, 0), 21.39],
[new Date(2014, 6, 2, 13, 0, 0, 0), 21.20],
[new Date(2014, 6, 2, 15, 0, 0, 0), 21.22],
[new Date(2014, 6, 2, 17, 0, 0, 0), 20.99],
[new Date(2014, 6, 2, 17, 30, 0, 0), 21.03],
[new Date(2014, 6, 3, 9, 0, 0, 0), 21.05],
[new Date(2014, 6, 3, 11, 0, 0, 0), 21.07],
[new Date(2014, 6, 3, 13, 0, 0, 0), 21.10],
[new Date(2014, 6, 3, 15, 0, 0, 0), 21.08],
[new Date(2014, 6, 3, 17, 0, 0, 0), 21.05],
[new Date(2014, 6, 3, 17, 30, 0, 0), 21.00],
[new Date(2014, 6, 4, 9, 0, 0, 0), 21.15],
[new Date(2014, 6, 4, 11, 0, 0, 0), 21.17],
[new Date(2014, 6, 4, 13, 0, 0, 0), 21.25],
[new Date(2014, 6, 4, 15, 0, 0, 0), 21.32],
[new Date(2014, 6, 4, 17, 0, 0, 0), 21.35],
[new Date(2014, 6, 4, 17, 30, 0, 0), 21.37],
]);
// Instantiate and draw our chart, passing in some options.
// var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
var options = {
title : 'AEX Stock: Nationale Nederlanden (NN)',
width : 1400,
height : 540,
legend : 'true',
pointSize: 5,
vAxis: { title: 'Price (Euro)', maxValue: 21.50, minValue: 20.50 },
hAxis: { title: 'Time of day (Hours:Minutes)', format: 'HH:mm', gridlines: {count:9} }
};
var formatNumber = new google.visualization.NumberFormat(
{prefix: '', negativeColor: 'red', negativeParens: true});
var formatDate = new google.visualization.DateFormat(
{ prefix: 'Time: ', pattern: "dd MMM HH:mm", });
formatDate.format(dataTable, 0);
formatNumber.format(dataTable, 1);
chart.draw(dataTable, options);
} // drawChart
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width:400; height:300"></div>
</body>
The example will:
Make a formatted hAxis with format HH:mm i.e. 18:00 for 6:00 PM.
Formats the data in the graph (hover over the data-plots) with day and time and the stock price.
Gives the graph gridlines.
I hope this example makes it clear how to handle the data in a correct way.
In chart the options object you could set the vAxis object with the field format and provide a string with the pattern you want to use here's an example:
new google.visualization.BarChart(document.getElementById('visualization'));
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
vAxis: {title: "Year", format: "yy"},
hAxis: {title: "Cups"}}
);
Look at the vAxis object.
For the string format you should look to http://userguide.icu-project.org/formatparse/datetime to build you the pattern you prefer.
You can use the hAxis.format or vAxis.format option. This allows you to specify a format string, where you use placeholder letters for different parts of your timeofday
To get rid of the seconds, you can set the format of the Y Axis like this:
var options = {
vAxis: { format: 'hh:mm' }
};

Custom tooltip text in Candlestick chart of google charts

I'm playing a bit with Google Charts API, and actually I need to change the default text showed in the tooltip of candlestick chart. Not only to change the style, but also it's content.
Does anyone knows how to achieve it?
Try this code to customize Tooltip content using html tags.
data.addRows([
['Mon', 20, 28, 38, 45, customTooltip('Monday')],
['Tue', 31, 38, 55, 66, customTooltip('Tuesday')],
['Wed', 50, 55, 77, 80, customTooltip('Wednesday')],
['Thu', 77, 77, 66, 50, customTooltip('Thursday')],
['Fri', 68, 66, 22, 15, customTooltip('Friday')]
]);
function customTooltip(text) {
return '<div style="padding:5px 5px 5px 5px;">' +
'<table id="medals_layout" style=" color:#db6acf; font-size:large">' + '<tr>' +
'<td><b>' + text + '</b></td>' + '</tr>' + '</table>' + '</div>';
}
Take a look at this jqfaq.com that has a working sample for Line chart
You can drop this into google's visualization playground:
function drawVisualization() {
data = new google.visualization.DataTable()
data.addColumn('string', 'Date');
data.addColumn('number');
data.addColumn('number');
data.addColumn('number');
data.addColumn('number');
data.addColumn({type:'string',role:'tooltip'});
data.addRow();
base = 10;
data.setValue(0, 0, 'Datapoint1');
data.setValue(0, 1, base++);
data.setValue(0, 2, base++);
data.setValue(0, 3, base++);
data.setValue(0, 4, base++);
data.setValue(0, 5, " This is my tooltip1 ");
data.addRow();
data.setValue(1, 0, 'Datapoint2');
data.setValue(1, 1, base++);
data.setValue(1, 2, base++);
data.setValue(1, 3, base++);
data.setValue(1, 4, base++);
data.setValue(1, 5, "This is my second tooltip2");
// Draw the chart.
var chart = new google.visualization.CandlestickChart(document.getElementById('visualization'));
chart.draw(data, {legend:'none', width:600, height:400});
}