Opensearch painless calculate elpased time between two timestamp - datetime

I have start and end timestamp, and I want to calculate the elpased time between them.
I created a dinamic field elapsed-time:
def result = 0;
def endTimestamp = doc['endTimestamp'].value.millis;
def startTimestamp = doc['startTimestamp'].value.millis;
return (endTimestamp - startTimestamp );
When I discover data, the elapsed time has always bad hours, but minutes and seconds are right.
What I am doing wrong?

Related

How to split two times using frequency in dart?

So, I need partition two times in dart(startTime and endTime) using an int value called frequency
Start time and End Time are DateTimes respectively. As for an example:
start time: 2021-07-20 10:00:00.000 // 10:00 AM
end time: 2021-07-20 16:00:00.000 // 04:00 PM
frequency: 30
so I need a list which will give my something like:
2021-07-20 10:30:00.000
2021-07-20 11:00:00.000
2021-07-20 11:30:00.000
2021-07-20 12:00:00.000
2021-07-20 12:30:00.000
.......
I have no idea what to do next. But I have created a method called returnTimeDifference which goes something like this:
Duration returnDuration (DateTime? startTime , DateTime? endTime) {
print(
"start time: $startTime \nend Time: $endTime",
);
Duration hourSpan;
workHourSpan = endTime!.difference(startTime !);
print(hourSpan);
return hourSpan;
}
For my above example the method will return 6:00:00.000000. I'm not sure if the value returned from the returnDuration can be used in any matter but I need help splitting the values of two date times into parts using the provided frequency.
N.B: Will it be easier to calculate the values if frequency was in actual Duration?
Repeatedly add your time interval to your start time in a loop until you reach the end time and collect the results. Using a Duration instead of an int for your time interval will be easier and will avoid ambiguity (in your example code, it's unclear if frequency represents a time in minutes, seconds, or if it's supposed to be the number if items you want in the resulting list).
Assuming that your start time and end time are meant to be exclusive endpoints, you could do:
/// Returns a list of [DateTime]s between (but not including) [start] and
/// [end], spaced by [period] intervals.
List<DateTime> getDateTimesBetween({
required DateTime start,
required DateTime end,
required Duration period,
}) {
var dateTimes = <DateTime>[];
var current = start.add(period);
while (current.isBefore(end)) {
dateTimes.add(current);
current = current.add(period);
}
return dateTimes;
}
void main() {
print(getDateTimesBetween(
start: DateTime(2021, 07, 20, 10),
end: DateTime(2021, 07, 20, 16),
period: Duration(minutes: 30),
));
}

How to create an event series with a start date and an end date

First of all, sorry if my English isn't good as I'm a french guy.
I have a problem with a google script I took on the internet that automatically inputs holliday in my calendar.
Let me explain in detail: I use a google form to get all the data I need to input my calendar, such as the name of the employee, the start date of his holliday, the end date, and other information like mail and stuff. The start date and end date are with hours to indicate at which hour start and finish the holliday.
Here's my problem, I use CreateEventSeries but when I use this, it creates a "bar" until the end date but I would like to have an event day by day, until the end date, that finish at 18pm.
Here's the code i use :
else if (approval == Approval.Approved && reason == Reason.Vacation) {
CalendarApp.getCalendarById(email)
.createEventSeries(
'CP',
startDate,
endDate,
CalendarApp.newRecurrence().addWeeklyRule()
.onlyOnWeekdays([CalendarApp.Weekday.MONDAY, CalendarApp.Weekday.TUESDAY, CalendarApp.Weekday.WEDNESDAY, CalendarApp.Weekday.THURSDAY, CalendarApp.Weekday.FRIDAY])
.until(endDate),
{
description: message,
sendInvites: true,
}
);
// Send a confirmation email.
let subject = 'Congés acceptés';
MailApp.sendEmail(additionalEmail, subject, message, );
row[Header.NotifiedStatus] = NotifiedStatus.Notified;
Logger.log(`Approved, calendar event created, row=${JSON.stringify(row)}`);
}
I don't know if I made myself clear.
I don't want an all-day event cause it's not visible enough on the calendar.
In short, I would like to create an event series day by day from 8 am until 18pm with a start date and an end date.
Does someone have a solution or a lead?
Best regards
Issue:
When creating an event series via createEventSeries(title, startTime, endTime, recurrence, options), the parameters startTime and endTime refer to the start and end time of the first event in the series, not of the series as a whole:
startTime: the date and time when the first event in the series starts
endTime: the date and time when the first event in the series ends
This endTime is completely different from what you want to set at until(endDate), which refers to when the series of events will finish.
Code snippet:
For example, if you want to have an event every day that lasts from 8 AM to 6 PM, from, let's say, 1 to 15 May, you would do this:
const startTime = new Date('May 1, 2021 08:00:00 GMT+01:00');
const endTime = new Date('May 1, 2021 18:00:00 GMT+01:00');
const endDate = new Date('May 15, 2021 18:00:00 GMT+01:00');
const recurrence = CalendarApp.newRecurrence().addWeeklyRule()
.onlyOnWeekdays([
CalendarApp.Weekday.MONDAY,
CalendarApp.Weekday.TUESDAY,
CalendarApp.Weekday.WEDNESDAY,
CalendarApp.Weekday.THURSDAY,
CalendarApp.Weekday.FRIDAY
])
.until(endDate)
CalendarApp.getCalendarById(email).createEventSeries('CP',startTime,endTime,recurrence);
Update:
Assuming you have installed an onFormSubmit trigger, your function could be something like this:
function createEventSeriesOnSubmit(e) {
const formResponse = e.response;
let itemResponses = formResponse.getItemResponses();
const itemNames = ["startDate", "endDate", "startHour", "endHour"];
const responses = itemNames.map(itemName => getResponseForItem(itemResponses, itemName));
const [startDay, endDay, startHour, endHour] = responses;
const startTime = new Date(`${startDay} ${startHour}`);
const endTime = new Date(`${startDay} ${endHour}`);
const endDate = new Date(`${endDay} ${endHour}`);
const recurrence = CalendarApp.newRecurrence().addWeeklyRule()
.onlyOnWeekdays([
CalendarApp.Weekday.MONDAY,
CalendarApp.Weekday.TUESDAY,
CalendarApp.Weekday.WEDNESDAY,
CalendarApp.Weekday.THURSDAY,
CalendarApp.Weekday.FRIDAY
])
.until(endDate)
CalendarApp.getCalendarById(email).createEventSeries('CP',startTime,endTime,recurrence);
}
Where "startDate", "endDate", "startHour", "endHour" are the names of the corresponding items in your Form. For example:
As you can see in the code sample, you can build the corresponding date to use in calendar by interpolating the date response and the time response, like this:
const startTime = new Date(`${startDay} ${startHour}`);
The resulting calendar has the series of events corresponding to the start hour, end hour, start date and end date that have been specified:

Complex calculation of the hours amount

I have a Pythonic system that stores student absences data in a SQLite database. Each row includes the start and end time of the absence, represented by the number of seconds since Jan 01 1970. I was asked to add a feature which limits the number of hours of absence per week.
It sounds easy to pull out the amount of hours, using a statement like this:
SELECT (sum(ending-starting)/3600)
FROM requests
WHERE student_id = {x}
AND starting BETWEEN {y} AND ({y}+604800)
AND approved = 1
The problem is that the limit must only be the hours defined as "mandatory presence." For example, if a user has defined the hours 8:00 to 17:00 as a "mandatory presence," an absence that begins on Sunday at 14:00 and ends on Monday at the same time, will be calculated in the code above 24 hours, while in practice it is only 9 hours.
"Mandatory presence" is defined in the database as two numerical parameters: "morning" and "evening" (always a round hour). Is there a way to make the calculation above taking into account these two numbers?
If it can not be done in sql, I would love to hear how to select the data in sql and then perform the calculation in python.
I believe the following may do what you wish :-
SELECT
(
sum((
(ending - starting)
-(
CASE WHEN starting < strftime('%s',date(starting,'unixepoch')||' 08:00')
THEN strftime('%s',date(starting,'unixepoch')||' 08:00') - starting
ELSE 0
END
+
CASE WHEN ending > strftime('%s',date(starting,'unixepoch')||' 17:00')
THEN ending - strftime('%s',date(starting,'unixepoch')||' 17:00')
ELSE 0
END
)
) /3600)
) AS ha, *
FROM requests
WHERE student_id = {x}
AND starting BETWEEN {y} AND ({y}+604800)
AND approved = 1
;
MikeT's answer is not entirely working, but it certainly helped me reach the desired result. Here's the perfect statement:
SELECT
(
sum((
(ending - starting)
-(
CASE WHEN starting < strftime('%s',date(starting,'unixepoch')||printf(' %02d:00', morning))
THEN strftime('%s',date(starting,'unixepoch')||printf(' %02d:00', morning)) - starting
ELSE 0
END
+
CASE WHEN ending > strftime('%s',date(ending,'unixepoch')||printf(' %02d:00', evening))
THEN ending - strftime('%s',date(ending,'unixepoch')||printf(' %02d:00', evening))
ELSE 0
END
)
) /3600.0
-(
(24-evening+morning)
*
(round(julianday(ending, 'unixepoch'))-round(julianday(starting, 'unixepoch')))
)
)) AS ha
FROM requests
INNER JOIN students ON requests.student_id = students.ID
INNER JOIN institutes ON students.inst_id = institutes.ID
WHERE student_id = {x}
AND starting BETWEEN {y} AND ({y}+604800)
AND approved = 1;
Thank you very much for your help!

Math with MySQL timestamps in groovy

I need to subtract one timestamp from another in groovy and get the number of hours that has passed. The timestamps are coming from MySQL. When I do simple math I get numbers of days rounded off to zero integers.
endDate - startDate
gives rounded integer
I want a result of 2.35 hours, etc.
You can use groovy.time.TimeCategory like so:
// create two timestamps
import java.sql.Timestamp
def dates = ['2012/08/03 09:00', '2012/08/03 10:30']
def (Timestamp a, Timestamp b) = dates.collect {
new Timestamp( Date.parse( 'yyyy/MM/dd hh:mm', it ).time )
}
// Then compare them with TimeCategory
use(groovy.time.TimeCategory) {
def duration = b - a
println "${duration.days}d ${duration.hours}h ${duration.minutes}m"
}
Which will print:
0d 1h 30m

comparison of two dates

how to compare values of 2 dates using actionscript
i executed this code in my program..
var time1:Date = new Date(Number(fromDate.substr(0,4)),Number(fromDate.substring(5,7))-1, Number(fromDate.substring(8,10)));
var time2:Date = new Date(Number(toDate.substr(0,4)),Number(toDate.substring(5,7))-1, Number(toDate.substring(8,10)));
if(time1.getTime() > time2.getTime())
{
Alert.show(time1 + ” is after ” + time2);
}
im getting error: Error: Unexpected end of token stream
AS3 doesn't support a time delta class like Python so this can actually be a little tricky. There are lots of things to be worried about when comparing dates:
daylight savings time (when the clocks change one hour in certain countries Spring and Fall)
time-zones
leap-years
The roughest way to do things is just to use the time property of a date object. This way you can get an accurate difference between two dates expressed in milliseconds:
var date1:Date = new Date(2001, 9, 12); // Oct. 12, 2001
var date2:Date = new Date(2010, 5, 22); // Jun. 22, 2010
var differenceInMilliseconds:Number = date2.time - date1.time;
Using this time property you can do things like check if one date is before or after another date. You can also do rough calculations on the distance between two dates by defining some constants:
const MILLISECOND_PER_SECOND:int = 1000;
const SECOND_PER_MINUTES:int = 60;
const MINUTES_PER_HOUR:int = 60;
const HOURS_PER_DAY:int = 24;
// ... etc ...
var differenceInSeconds:Number = differenceInMilliseconds / MILLISECOND_PER_SECOND;
var differenceInMinutes:Number = differenceInSeconds / SECOND_PER_MINUTES;
var differenceInHouse:Number = differenceInMinutes / MINUTES_PER_HOUR;
var differenceInDays:Number = differenceInHouse / HOURS_PER_DAY;
Once you get to the level of days you could get problems with daylight savings time since the change of 1 hour can make it seem like a full day has passed when it really hasn't. After days and into weeks or months you run into leap year problems.
Assuming your string processing code correctly gives you valid date objects, just use the ObjectUtil.dateCompare function to compare 2 dates:
http://livedocs.adobe.com/flex/3/langref/mx/utils/ObjectUtil.html#dateCompare%28%29
if( ObjectUtil.dateCompare(date1, date2) == 1 ){}
I'm pretty sure that the return types defined in the ASDocs are wrong.
It'll actually return -1 if a is null or before b; 1 if b is null or before.
If you have two dates as Date objects already, just compare them. e.g. a.getTime() > b.getTime().
If they are strings, see their format is acceptable by the default Date.parse() function. If not, you may have other work to do.
Let's see your values first, shall we?
private function differenceBetweenDates(date1:Date, date2:Date):Number{
var MS_PER_DAY:uint = 1000 * 60 * 60 * 24;
var tempDate:Date = new Date(date2.time - date1.time);
var difference:Number =
Math.abs(Math.round((tempDate.time / MS_PER_DAY)));
return difference;
}
I have achieved comparing dates succesfully using below code:
//here i have to compare two dates ,these are startdate and enddate.
// gets millisecs counts from 1970 midnight till sellected start date
var Starttimecounts : Number = popJobWin.DFStartDate.selectedDate.time;
// gets millisecs counts from 1970 midnight till sellected end date
var Endtimecounts : Number = popJobWin.DFEndDate.selectedDate.time ;
if (Starttimecounts > Endtimecounts)
{
Alert.show('end date should not lesser than start date..wrong!');
//replace your logic here
}
else
{
Alert.show('correct!');
//replace your logic here
}

Resources