How to get the minutes from a timespan in KQL - time

I wanted to extract the time in minutes for a Kusto query I was working on. I have a cloumn where timespan is represented in the following format (HH:MM:SS.MilliSeconds) 01:18:54.0637555. I wanted to extract the number of minutes from this in this case 78 minutes. How can I do that ?

Try dividing the timespan value by 1min, as explained here: https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/datetime-timespan-arithmetic

If you just need to print the timespan parts, you can create a small user-defined function to collect each part of the timespan:
let print_timespan = (input: timespan) {
iif(
isempty(input), "",
strcat(
format_timespan(input, 'dd'), "d ",
format_timespan(input, 'hh'), "h ",
format_timespan(input, 'mm'), "m ",
format_timespan(input, 'ss'), "s ")
)
};
let t = time(29.09:00:05.12345);
print print_timespan(t)
---
29d 09h 00m 05s

Related

Java 8 - SQL Timestamp to Instant with properly formatted time

I've read through the available q and a on SO, but nothing I have found answers my question of how to format my time in 12hour format.
Following is my code that runs a query on a MySQL database and returns results, checking to see if an appointment is within 15 minutes of login so an alert can pop.
public void apptCheck(int userId) throws SQLException {
// this method checks for an appointment occurring within 15 minutes of login
Statement apptStatement = DBQuery.getStatement();
String apptQuery = "Select apt.start, cs.customerName from DBName.appointment apt "
+ "JOIN DBName.customer cs ON cs.customerId = apt.customerId WHERE "
+ "userId = " + userId + " AND start >= NOW() AND start < NOW() + interval 16 minute";
apptStatement.execute(apptQuery);
ResultSet apptRs = apptStatement.getResultSet();
while(apptRs.next()) {
Timestamp apptTime = apptRs.getTimestamp("start");
ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
Alert apptCheck = new Alert(AlertType.INFORMATION);
apptCheck.setHeaderText(null);
apptCheck.setContentText(languageRB.getString("apptSoon") + " " + apptTime.toInstant().atZone(ZoneId.systemDefault()));
apptCheck.showAndWait();
}
My result is:
I want the time to display 3:00, not the 19:00 - 06:00. How can I make that happen?
ZonedDateTime zonedDateTime=ZonedDateTime.of(apptTime.toLocalDateTime(),ZoneId.systemDefault());
You can use ZonedDateTime and format the time as you want.
docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html ZonedDateTime has a lot of features you can see all here and you can get the hour, minute, day etc.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
String formattedString = zonedDateTime.format(formatter);
if you only want time in 12hour format you can use this
I found the solution which will perform the UTC to local time conversion and then format the time so that the resulting alert is in 12 hour time format without the date or time zone info. Here is the full code:
while(apptRs.next()) {
Timestamp apptTime = apptRs.getTimestamp("start");
// perform time conversion from UTC to User Local Time
ZoneId zidApptTime = ZoneId.systemDefault();
ZonedDateTime newZDTApptTime = apptTime.toLocalDateTime().atZone(ZoneId.of("UTC"));
ZonedDateTime convertedApptTime = newZDTApptTime.withZoneSameInstant(zidApptTime);
ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
Alert apptCheck = new Alert(AlertType.INFORMATION);
apptCheck.setHeaderText(null);
// set the Alert text and format in 12 hour format
apptCheck.setContentText(languageRB.getString("apptSoon") +
convertedApptTime.toInstant().atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("h:mm a")) + ".");
apptCheck.showAndWait();
}

VBS Object Required Error manipulating strings

I am trying to create a simple script that prompts the user for their birthday, formatted as 10.02.20, then takes that string and turns it into text, such as October 2nd 2020. I have the following code:
Dim bd, message, title ' define variables
title = "What is your birthday?" ' set variable
message = "Format like so: 12.15.07; 3.03.05" ' set variable
bd = InputBox(message, title) ' prompt user
Dim year
year = bd.Substring(6, 2)
Dim month
month = bd.Substring(0, 2)
Dim day
day = bd.Substring(3, 2)
msgbox bd ' for testing
call msgbox(year + month + day) 'also testing
And I am getting an error after the prompt, ...\Desktop\test.vbs(8, 1) Microsoft VBScript runtime error: Object required: '12.23.03' and I am not sure what it means, Object Required.
Any fixes or suggestions would be very much appreciated.
You cannot use Substring in VBScript. You can use Mid instead:
Dim year
year = Mid(bd, 7, 2)
The first character in a string is at position 1, not 0, so I adjusted your parameter from 6 to 7.
Also, to concatenate strings, although + works, you can also use &:
call msgbox(year & month & day)
You can use this function in vbscript : FormatDateTime(date,format)
Parameter Description
date Required.
Any valid date expression (like Date() or Now())
format Optional.
A value that specifies the date/time format to use can take the following values:
0 = vbGeneralDate - Default. Returns date: mm/dd/yyyy and time if specified: hh:mm:ss PM/AM.
1 = vbLongDate - Returns date: weekday, monthname, year
2 = vbShortDate - Returns date: mm/dd/yyyy
3 = vbLongTime - Returns time: hh:mm:ss PM/AM
4 = vbShortTime - Return time: hh:mm
Dim Title,Input
Title = "format date"
Input = InputBox("Enter your date of Birthday !",Title,"10.02.20")
Input = FormatDateTime(Replace(Input,".","/"),1)
MsgBox Input

DateSerial overflow with dates greater than 17/09/2059

I am currently working on a VB6 project that handles event data transmit by UK rail stock. Occasionally the trains 'gets confused' about the date and will transmit events dated wildly in the future, I have seen events dated as far as 2088. The date is transmit as Unix time (seconds from 1/1/1970).
I understand what the issue is, i am just struggling to find a solution. The issue appears to be when the date exceeds '17/09/2059' it overflows the integer used for the 'day' that DateSerial can handle. The code below is the line where the overflow occurs, so when 'intDays+1' is > 32767.
UnixTimestampToDateTime = DateSerial(1970, 1, intDays + 1) + TimeSerial(intHours, intMins, CInt(intSecs))
The goal is to convert Unix time into the following format "dd/mm/yyyy hh:mm:ss". Can i get DateSerial to work beyond this date limitation or do i need to completely change how i calculate the date? Any help would be appreciated. Cheers.
You could initialize your result to 01/01/1970 and then add the required seconds:
Dim unix_time As Currency
Dim max_long As Long
Dim result As Variant
' Determine unix time
unix_time = .....
' Initialize result to 01/01/1970 00:00:00
result = DateSerial(1970, 1, 1) + TimeSerial(0, 0, 0)
' Determine maximum number of seconds we can add in a single call
max_long = 2147483647
' Add desired time
While unix_time > max_long
result = DateAdd("s", max_long, result)
unix_time = unix_time - max_long
Wend
result = DateAdd("s", CLng(unix_time), result)
Actually it is quite trivial to come up with a replacement version of DateSerial that accepts Long for days, e.g. try this:
Private Function MyDateSerial(ByVal Year As Integer, ByVal Month As Integer, ByVal Day As Long)
MyDateSerial = DateSerial(Year, Month, 1) + Day - 1
End Function
Here is a simple use-case to test it
Debug.Print MyDateSerial(1970, 1, 30000), DateSerial(1970, 1, 30000)
19.2.2052 19.2.2052

Formatting Date in Title

I have figured out how to get a date (from a report parameter) in my title:
[#Start]
Annoying that I cannot do "this" which is what I really want to do
[#Start] to [#End]
But I can deal with that; it just means 3 titles instead of one.
However, what I cannot seem to figure out is how to format the date:
I Get: 11/13/2011 12:00:00 AM
I want: Nov 13th
I could live with 11/13/2011
For the suffix I recommend to use the switch function:
=Format(Parameters!Start.Value, "MMM-dd") +
Switch(Format(Parameters!Start.Value, "dd") >= 11 And Format(Parameters!Start.Value, "dd") <= 13 , "th",
Right(Format(Parameters!Start.Value, "dd"), 1) = "1", "st",
Right(Format(Parameters!Start.Value, "dd"), 1) = "2", "nd",
Right(Format(Parameters!Start.Value, "dd"), 1) = "3", "rd",
1 = 1, "th")
Or you can make a user function to do the same...
It took awhile to figure out that the "expr" field can be very complex.
The following gives me very close to what I need:
=Format(Parameters!Start.Value, "MMM-dd") + " to " + Format(Parameters!End.Value, "MMM-dd")

Is it normal sqlite.fetchall() is slow?

I have an SQL query that selects from two inner joined tables. The select statement takes about 50 seconds. However, the fetchall() takes 788 seconds for only 981 results:
time0 = time.time()
self.cursor.execute("SELECT spectrum_id, feature_table_id "+
"FROM spectrum AS s "+
"INNER JOIN feature AS f "+
"ON f.msrun_msrun_id = s.msrun_msrun_id "+
"INNER JOIN (SELECT feature_feature_table_id, min(rt) AS rtMin, max(rt) AS rtMax, min(mz) AS mzMin, max(mz) as mzMax "+
"FROM convexhull GROUP BY feature_feature_table_id) AS t "+
"ON t.feature_feature_table_id = f.feature_table_id "+
"WHERE s.msrun_msrun_id = ? "+
"AND s.scan_start_time >= t.rtMin "+
"AND s.scan_start_time <= t.rtMax "+
"AND base_peak_mz >= t.mzMin "+
"AND base_peak_mz <= t.mzMax", spectrumFeature_InputValues)
print 'query took:',time.time()-time0,'seconds'
time0 = time.time()
spectrumAndFeature_ids = self.cursor.fetchall()
print time.time()-time0,'seconds since to fetchall'
Is there a reason why fetchall() takes so long? Doing:
while 1:
info = self.cursor.fetchone()
if info:
<do something>
else:
break
is just as slow as :
allInfo = self.cursor.fetchall()
for info in allInfo:
<do something>
By default fetchall() is as slow as looping over fetchone() due to the arraysize of the Cursor object being set to 1.
To speed things up you can loop over fetchmany(), but to see a performance gain, you need to provide it with a size parameter bigger than 1, otherwise it'll fetch "many" by batches of arraysize, i.e. 1.
It is quite possible that you can get the performance gain simply by raising the value of arraysize, but I have no experience doing this, so you may want to experiment with that first by doing something like:
>>> import sqlite3
>>> conn = sqlite3.connect(":memory:")
>>> cu = conn.cursor()
>>> cu.arraysize
1
>>> cu.arraysize = 10
>>> cu.arraysize
10
More on the above here: http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.fetchmany
If you are running a complex query, try to create a table using that complex query and then run a select on the created table so the performance is good.

Resources