Hi, I need to display data from a table (vw_tracking_resource_events), but only 14 days of data for a certain time (18:00 to 19:00) - postgresql

I use PostgreSQL
I can run a single query per day, but it will take a long time to go through every day.
The "zone" and "reader" also changes, so to run single queries every time will keep me up until late.
If at best I can only change the "reader" and "zone" every time it would help. The main "PAIN" I have, is to change the dates every time. It will be from 2022 11 18 18:00 to 2022 12 01 19:00.
P.S - I'm new to SQL, please be gentle :)
My current query:
select * from vw_tracking_resource_events
where "when_enter_dt_timezone" between '2022 11 18 18:00:00' and '2022 11 18 19:00:00'
and "zone" = '085 Level'
and "site" = 'MK'
and "reader" = 'RV Shaft'
and "group" = 'Lamp'

If you cast your field to separate and compare the date part and the time part to desired ranges, it becomes super easy:
WHERE when_enter_dt_timezone BETWEEN '2022-11-18' AND '2022-12-01T23:59:59.999'
AND when_enter_dt_timezone::time BETWEEN '18:00' AND '19:00'
Edit:
#Stefanov.sm makes a very good point regarding the casting of the timestamp to type date (1st criterion above) if an index can be used to retrieve data.
I corrected the query to take his remark.
Disclaimer: With when_enter_dt_timezone::date BETWEEN ... AND 2022-12-01, you include e.g. 2021-12-01T18:30.
Without the cast, the upper bound 2022-12-01 is implicitly set to midnight (morning); you will either have to change the upper bound to 2022-12-02 (which #Stefanov.sm suggested and works very well since you have a condition on the time anyway) or set your upper bound to 2022-12-01T23:59:59.999 (which is what I did above, although only to draw your attention to this specific issue).

You can try something like this to get records for the last 14 days between 6:00 p.m. and 7:00 p.m.
select * from vw_tracking_resource_events
where when_enter_dt_timezone > current_date - interval '14' day and
when_enter_dt_timezone::time between time '18:00' AND time '19:00'
Demo in sqldaddy.io
Modified using #Atmo notes
and #a_horse_with_no_name

Related

Why is Date.getMinutes() returning 2 for the time 4:00 PM?

I'm creating a customized function that does some calculations for a given time.
When a time is entered in a cell, for example 4:00 PM, this is automatically converted into a date, in this case 12/30/1899 16:00:00 and when the function getTheMinutes() is called, it returns 2 instead of 0.
function getTheMinutes(dateTime){
return dateTime.getMinutes();
}
The behavior of the function is different if it's used for a most recent date like 5/1/2019 16:00:00.
I want the user to be able to just write a time in a cell then use the customized function in another cell. Please let me know your thoughts.
Now that you have indicated the time zone for your spreadsheet I can confirm what #RobG deduced almost a day ago, which is that Guatemala adjusted its difference relative to UTC. Something you have confirmed is treated as by two minutes with effect from October 5, 1918.
More specifically, the adjustment was of 2 minutes and 4 seconds and effective from 03:00 that day:
(Source IANA Version 2019b file northamerica.)
There have been very many such minor adjustments around the world over the years (even between towns in the same country) and adjustments continue, though usually of a whole hour – between 'standard' and Summer time. Sheets has very properly recognised that "normal arithmetic" 'does not work' across such a transition and while noon yesterday to noon today for example is normally, for any one specific location, a difference of 24 hours it is often 23 hours or 25 hours on the day that clocks go forward/back.
And the moral of the story is to beware of obliging Sheets to assume, for want of a specific date, that is has the index number 0 - i.e. is December 30, 1899.
I made some testing, and I found out that the formula is giving a wrong result any minute before 10/5/1918 0:03:00, from that DateTime on, the formula is working as expected.
Here is my sheet https://docs.google.com/spreadsheets/d/1psm8_GJYRczO53TILJCOzo0p4GpnS-ooiGWqOJrC8ZU/edit?usp=sharing
I would need to do a date validation in my customized formula to make it useful. I don't know why google sheets is choosing that date as default when just a time is typed in a cell, I think it should be improved.

Cleaner way of dealing with dates in java / Quartz

In order to programmatically schedule a job one day ahead (using quartz) I had to come up with this mess of code:
Date.from(LocalDateTime.from(Instant.now()).plusDays(1).toInstant(ZoneOffset.ofHours(-3)))
Isn't there a way of making this monstruous piece of code more clean, readable?
My goal is to simple pick this moment and add one day to it, no concerns about timezones or little differences in the duration of some given days.
EDIT
To be more specific, I need a java.util.Date that represents one day more than when it is created.
The title you picked asks for dates in Java in a general sense, but your question and your tags show that you might be interested in some Quartz-specific solutions, like these (assuming you're using TriggerBuilder):
TriggerBuilder tb = ...; // initialize your tb
// Option 1
Trigger trigger = tb
.withSchedule(/* pick your flavor */)
.startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.DAY))
.build();
// Option 2
LocalDateTime now = LocalDateTime.now();
Trigger trigger2 = tb
.withSchedule(/* pick your flavor */)
.startAt(DateBuilder.tomorrowAt(now.getHour(), now.getMinute(), now.getSecond()))
.build();
For more info check the DateBuilder API.
There are two forms with no preference I know of for one or the other. Either this one:
Date sameTimeTomorrow = Date.from(Instant.now().plus(Duration.ofDays(1)));
Or this:
Date sameTimeTomorrow = Date.from(Instant.now().plus(1, ChronoUnit.DAYS));
Beware, however, that this adds 24 hours without any consideration of summer time or other anomalies. For example: In my time zone summer time ends in the night between October 27 and 28. So if I run the above on October 27 at 12 noon I will hit October 28 at 13 in my time zone because the time has changed. If I need to hit 12 noon again, I need:
Date sameTimeTomorrow = Date.from(
ZonedDateTime.now(ZoneId.of("America/Sao_Paulo")).plusDays(1).toInstant());
Please substitute your correct time zone.

How to handle dates in neo4j

I'm an historian of medieval history and I'm trying to code networks between kings, dukes, popes etc. over a period of time of about 50 years (from 1220 to 1270) in medieval Germany. As I'm not a specialist for graph-databases I'm looking for a possibility to handle dates and date-ranges.
Are there any possibilities to handle over a date-range to an edge so that the edges, which represents a relationship, disappears after e.g. 3 years?
Are there any possibility to ask for relationships who have their date-tag in a date-range?
The common way to deal with dates in Neo4j is storing them either as a string representation or as millis since epoch (aka msec passed since Jan 01 1970).
The first approach makes the graph more easily readable the latter allows you to do math e.g. calculate deltas.
In your case I'd store two properties called validFrom and validTo on the relationships. You queries need to make sure you're looking for the correct time interval.
E.g. to find the king(s) in charge of France from Jan 01 1220 to Dec 31st 1221 you do:
MATCH (c:Country{name:'France'})-[r:HAS_KING]->(king)
WHERE r.validFrom >= -23667123600000 and r.validTo <=-23604051600000
RETURN king, r.validFrom, r.validTo
addendum
Since Neo4j 3.0 there's the APOC library which provides couple of functions for converting timestamps to/from human readable date strings.
You can also store the dates in their number representation in the following format: YYYYMMDD
In your case 12200101 would be Jan 1st 1220 and 12701231 would be Dec 31st 1270.
It's a useful and readable format and you can perform range searches like:
MATCH (h:HistoricEvent)
WHERE h.date >= 12200101 AND h.date < 12701231
RETURN h
It would also let you order by dates, if you need to.
As of Neo4J 3.4, the system handles duration and dates, see the official documentation. See more examples here.
An example related to the original question: Retrieve the historical events that happened in the last 30 days from now :
WITH duration({days: 30}) AS duration
MATCH (h:HistoricEvent)
WHERE date() - duration < date(h.date)
RETURN h
Another option for dates that keeps the number of nodes/properties you create fairly low is a linked list years (earliest year of interest - latest year), one of months (1-12), and one of dates in a month (1-31). Then every "event" in your graph can be connected to a year, month, and day. This way you don't have to create a new node for every new combination of a year month and day. You just have a single set of months, one of days, and one year. I scale the numbers to make manipulating them easier like so
Years are yyyy*10000
Months are mm*100
Date are dd
so if you run a query such as
match (event)-[:happened]->(t:time)
with event,sum(t.num) as date
return event.name,date
order by date
You will get a list of all events in chronological order with dates like Janurary 17th, 1904 appearing as 19040117 (yyyymmdd format)
Further, since these are linked lists where, for example,
...-(t0:time {num:19040000})-[:precedes]->(t1:time {num:19050000})-...
ordering is built into the nodes too.
This is, so far, how I have liked to do my event dating

Matlab- Changing uniques date code values to more manageable data

I have a variable called sentDate which stores the month and day from Nov 27th - Dec 6th.Each day has a number of sentiment ratings that it represents therefore I need to assign unique day codes to each day so I can perform...
allSents(dayCodes==1)
So far I have managed to assign day codes using...
[a,b,dayCodes]=unique(sentDate);
[d,e,allSents]=unique(sentiment);
However the day codes take the last digit on the date e.g 27th becomes 7, 28th becomes 8, etc. I need it so the day codes start from 1 and increase for each day until the 6th of December, therefore 1-11.
Any idea on how I may do this ?
have you tried the datenum function? then subtract off whatever offset to give the appropriate start day number.
For those who may have a similar problem, by specifying stable in as a parameter e.g
[a,b,dayCodes]=unique(sentDate,'stable');
Will specify the daycodes in the same order as in sentDate.

How to assign whether a specific date is during work hours or not. (SPSS)

Hi i'm new to this site so forgive me if i didn't search for this question thoroughly enough!
Basically i'm doing a research project where one of the variables is whether an xray was performed during normal work hours or not. Work hours include Monday-Friday, 8am-5pm.
I have input the date and time of each xray using separate variables
-[date+time (dd.mm.yyyy hh:mm)]
-[time (hh:mm)].
I was planning on inputing this information manually but i though that surely there is way to automate this and since i have next to zero experience with SPSS i thought i should ask you lovely people to help me out!
Thankyou in advance
Below I go through a quick example utilizing the xdate function to extract the day of week, and then construction an if statement to identify whether these date-times fall within workhours.
*Making example data.
data list free / xray_date (ADATE10) xray_time (TIME5).
begin data
7/6/2011 2:21
10/11/2011 15:42
07/06/2011 02:21
3/15/2011 0:21
end data.
*Here is example to find day of week name, 1 is Sunday and 7 is Saturday.
compute day_week = Xdate.Wkday(xray_date).
*to identify times of day in an if statement we need to make specific variables.
string begin_time end_time (A5).
compute begin_time = "08:00".
compute end_time = "17:00".
alter type begin_time end_time (TIME5).
*Then you can just make an if statement to identify whether a date-time meets your requirements.
compute workhours = 0.
if day_week >= 2 and day_week <= 6 and xray_time >= begin_time and xray_time <= end_time workhours = 1.
For this particular example, if you run the command list all. the resulting output will be;
xray_date xray_time day_week begin_time end_time workhours
07/06/2011 2:21 4.00000 8:00 17:00 .00000
10/11/2011 15:42 3.00000 8:00 17:00 1.00000
07/06/2011 2:21 4.00000 8:00 17:00 .00000
03/15/2011 0:21 3.00000 8:00 17:00 .00000
You can see the record with 10/11/2011 was appropriately classified as it is a Tuesday and within working hours. All of the other records are not between 8 am and 5 pm, so are initialized to the zero value for the workhours variable.