javascript Calculating moment subtraction - javascript

I want to subtract the ones formatted by one and two respectively.
ones and twos are json values ​​and moment was applied.
But in substract , an error occurs saying there is no string in substract.
const one = ones.format("YYYY-MM-DD HH:MM:SS"); // 2023-01-18 22:01:42
const two = twos.format("YYYY-MM-DD HH:MM:SS"); // 2023-01-16 05:01:21
const result = one.subtract(two);
I want to subtract one and two values ​​from each other and put them into a variable. How should I handle it?

Related

how to send datetime dataframe to django template and plot it in js using plotly

I have a data-frame and I want to send it in my Django template.
dummy code in views.py:
def graphs(request):
df_new = pd.read_excel("/home/cms/cms/static/Sensorik.xlsx")
times = df_new.loc[:, df_new.columns[0]].to_json(orient='records')
# columns[0] contains datetime values
data_color = df_georgian.loc[:, df_georgian.columns[2]]
color = data_color.to_json(orient='records')
context = {
'times': times,
'data_color': color,
...
}
return render(request, 'graphs/graphs.html', context)
In my template, I get these data like the following:
<script>
var times = {{ times|safe }};
console.log('index: ', typeof(index));
var color = {{ data_color|safe }};
</script>
the color variable is totally ok but the times variable when get to JSON format turns from 2018-05-29 08:09:00 format to something like it:
element: 1528108200000
I want to be able to plot the color based on times to get a line graph with plotly. i.e. I want to show times as x-ticks of my plot.
any suggeston on
1- how to send datetime dataframe to django template?
or
2- how to convert element: 1528108200000 into a datetime in js to plot it as x-ticks?
Whenever you see something that should be a date or time expressed in a large number like the 1528108200000 format, that means it is or is similar to a UNIX timestamp—the number of seconds past January 1, 1970. In this case, the length of the timestamp indicates that it's milliseconds, not seconds, so it's not exactly a UNIX timestamp but is very close.
Milliseconds since January 1, 1970 is the way that JS internally stores Date objects, which is interesting because it means some sort of conversion is probably happening on the JS side, not the python side (where you'd usually get ISO format or UNIX Timestamps).
In any case, it's pretty easy to solve on the JS side because you can simply parse the number:
dateObject = new Date(1528108200000);
If you do that parsing and pass the data to Plotly as Date objects, Plotly should be able to recognize your dates.
A simple way to do that would be:
const times = [1528108200000, 1528108200000, 1528108200000]
const parsed = times.map(time => new Date(time))
assuming your times variable is just an array of these integers.

Print For-Loop results in a table

I have 10 rows of data on my input step, i transform them in a for-loop and i should get more than 10 rows, but in this case i get the last transform of each iteration that the loop have for each data
I tried to use appendToFile() but the result data is not useful and pentaho read it as a unique header
On my alert() method i can see that the for loop transform the data.
var PERIODO = 2
var i
var fecha_final
//var ruta_acess ="D:\TEST.accdb"
//var contenido
////var contenido2
//var arreglo_completo
for (i=0; i<=PERIODO; i++){
fecha_final = dateAdd(FECHA_INICIO,"d",i)
Alert(i)
}
As I show in the below photo i get only 10 records and in the other photo appears the result that i want that are the results data of each iteration of the for-loop
Modified JavaScript value photo:
Expected result:
Obtained result:
For loops are not really a thing in PDI. Transformations work on sets of rows that flow through the steps, so it's best for performance and stability to use that mindset.
In your scenario each incoming row should end up as three copies, but with different calculated values based on a single new field (with values 0,1,2).
The way to do this in PDI is with a Join rows (cartesian product) step. It takes two sets of input rows and outputs a row for every combination of input rows, possibly filtered by defining a key field that has to match. So if you have 10 rows in the main input and 3 rows in the second, it will output 30 rows.
You will first need to create a data grid as the second input. Define a single integer field, name it something clear and on the second tab fill three rows with 0, 1 and 2 respectively.
Connect both inputs to the Join rows step. You don't need to configure any matching key.
The output of the Join step will be three rows for each input row, one with each of the values 0, 1, 2. Connect that output to a Calculator step and use the calculation Date A + B days to replace the logic from your javascript step.
what i mean is that in the obtained result photo the "i" variable only shows the value of "3" and i would like to have "1", "2" and "3"
to solve this i used
var row = createRowCopy(getOutputRowMeta().size())
var idx = getInputRowMeta().size()
row[idx++] = DPROCESS
this add a row for each result of the iteration.
before the tranformation result showed to me only the last value of each loop.

Javascript combine and sort arrays

Beginner
I have 3 arrays, i would like to combine and sort, according to date and time.
All 3 arrays, only have date and time values.
Example:
var slackStart = []; //time the current starts for the week.
var CurrentTurn = []; //time the current turns for the week.
var slackStop = []; //time the current stops for the week.
Output slackStart (contains all starting times for the week):
[ "2017-10-24T03:15:36Z", "2017-10-24T09:13:44Z", "2017-10-24T15:41:27Z", "2017-10-24T21:40:27Z", "2017-10-25T03:47:20Z"]
I need to combine the 3 arrays and sort according to date and time. I also need to know from which array the value came. If its slackStart, i know its the starting time for the current.
I want to display it like this.
Current start: 11/11/17 12:00
Current turn: 11/11/17 14:00
Current Stop: 11/11/17 17:00
Combining the arrays is easy but how can i know from which array it came?
I tried using keys but struggled a bit.
Any help would be appreciated.
You can combine arrays simply by calling the 'concat' method:
var aryA = [1,2,3]
,aryB = [4,5,6]
,aryResult = aryA.concat(aryB);
'aryResult' will contain [1,2,3,4,5,6], in terms of identifying where it came from, are the dates going to be unique?
If not then you should forget an array and convert to an object with unique key for each entry, then you can simply use the key.
var objResult = {};
for( var idx in aryResult ) {
objResult["k" + idx] = aryResult[idx];
}
The above will translate the combined array into an object with each member having a key that starts with k followed by the array index.

barChart plot with time dimension

I would like to make a bar chart where x-axis is date e.g. 2017-08-12, and the y value is the number of data rows (i.e. records count) on the same date.
// get data into right format
var dateFormat = d3.time.format("%Y-%m-%d");
pageViews.forEach(function(d) {
d['timestamp'] = dateFormat.parse(d['timestamp'].slice(0,10));
d['timestamp'].setDate(1);
});
// Create Crossfilter instance
var cf = crossfilter(data);
var dateDim = cf.dimension(function(d) {return d['timestamp'];});
var numByDate = dateDim.group();
but if I do
console.log(numByDate.top(Infinity));
this returns 5 elements that are the first day of each month, so the group I have is in terms of Year-Month instead of Year-Month-Day, how can I resolve this?
I looked into this crossfilter.js: group data by month, but it did not work, after using .all() I still get the same thing back.
And I tried this:
var numByDate = dateDim.group(function(d) {return d['timestamp'];});
it just returns me an empty object.
So this is a result of my unfamiliarity with js and copy paste example code ...
The issue comes from misuse of the setDate method,
setDate(1)
would just set the day of the month in the data to the first day, so the group method would only have several unique dates to work with.

Display specific parts of array

This code is creating an array, dateArray, from the parameter, date3, which is being passed through a function.
The data being passed through that function is a full date in the format, "12312015". The variable month should break off the first two characters of the array, dateArray. Then the variable Smonth converts the month array back into a string. The last line is then supposed to display the string "12" through the HTML form in a textbox. When the button on the form is pressed the function runs but it displays nothing.
var dateArray = [date3];
var month = dateArray.slice(1, 2);
var Smonth = month.toString();
VerifyForm.dobBox.value = Smonth;
The problem is you are creating an array dateArray with only 1 item in it which is the date string, so slicing it from 1 to 2 will return an empty array not the first and second characters of the original string.
Since date3 is a string, you can use String.substring() to extract the first 2 characters
var month = date3.substring(0, 2);
VerifyForm.dobBox.value = month;
After this
dateArray = [date3];
the dateArray contains single element at index 0. And here
dateArray.slice(1, 2);
you are trying to get range from 1 to 2 elements. But they are not there.
So you are getting nothing - empty array.
The dateArray you're creating is an array with a SINGLE value.
the slice function you're using is used to 'slice' up arrays with MULTIPLE values.
To achieve what you're trying to achieve you need to use substring.
Example:
VerifyForm.dobBox.value = date3.substring(0,2);

Categories