GQL SELECT by date - google-app-engine

I have this model:
class Entry(db.Model):
title = db.StringProperty()
url = db.URLProperty()
date = db.DateTimeProperty(auto_now=True)
image = db.URLProperty()
weight = db.IntegerProperty()
category = db.StringProperty()
desc = db.TextProperty()
I have lots of entries each day, how do I SELECT only today's entries by using GGL ?
since query like this does not return any results ( but I know that there is results ):
SELECT * FROM Entry WHERE category = 'news' and date = '2012-03-12' ORDER BY weight DESC

It's not saved as a string, but as a datetime like object.
The right-hand side of a comparison can be one of the following:
a datetime, date, or time literal, with either numeric values or a
string representation, in the following forms:
DATETIME(year, month, day, hour, minute, second)
DATETIME('YYYY-MM-DD HH:MM:SS')
DATE(year, month, day)
DATE('YYYY-MM-DD')
TIME(hour, minute, second)
TIME('HH:MM:SS')
http://code.google.com/appengine/docs/python/datastore/gqlreference.html
So in your example, use either of these.
date = DATE('2012-03-12')
date = DATE(2012,03,12)
For datetime the time is by default set to 00:00, so equality comparison will fail therefore you must use > to compare
SELECT * FROM Entry WHERE date > DATETIME(yyyy,mm,dd)

If anyone need to looking for a datetime, it works for me in GQL:
select * from tableName where recordDate >= DATETIME('2018-10-07T00:56:36z')
I hope it help to anyone

Related

How to get the begin date by tri-annual period (the year is devided into 3 parts)

I want to get the beginning date of each one third part of year, when I give a date the return must be the first day (date) of this one-third part.
Example: if the parameter is '1-april-2023' the return must be '1-jan-2023'
if the parameter is '1-june-2023' the return must be '1-may-2023'
and so on
We can do some date math by adding 4 months times the (month-1)/4 to the beginning of the year.
CREATE FUNCTION dbo.GetThirdOfYear(#d date)
RETURNS TABLE WITH SCHEMABINDING
AS
RETURN
(
SELECT Third = DATEADD(MONTH,
4*((MONTH(#d)-1)/4),
DATEFROMPARTS(YEAR(#d),1,1))
);
Sample usage, given a table called Events with a column called EventDate:
SELECT e.EventDate, f.Third
FROM dbo.Events AS e
CROSS APPLY dbo.GetThirdOfYear(e.EventDate) AS f;
Example db<>fiddle (and how I got there).

Extracting date from varchar with timezone in snowflake

I have some sample data in snowflake as follows;
created_at
----------
2022-06-10T18::35::57
2022-06-10T18::35::57
The datatype of this column is VARCHAR(16777216), I am trying to filter for the rows with date June 10,2022. Here is my query;
select *
from table
where to_date(created_at) = date('2022-06-10', 'yyyy-mm-dd');
But this gives me following error; Date '2022-06-10T18::35::57' is not recognized. If we replace to_date by try_to_date then we get 0 rows. Unfortunately I can't go to backend and change the properties of the table. Therefore, I need to resort to sql datetime functions.
Can I please get help here, on how to fix above errors? thanx
Using LEFT to get date part:
where to_date(LEFT(created_at, 10), 'YYYY-MM-DD') = date('2022-06-10', 'YYYY-MM-DD');
There are two issues here -
1 - It is not a date but a timestamp
2 - usage of '::' rather then standard ':' in time portion
Below will not work as its not a date -
with date_cte(created_at) as
(select * from values
('2022-06-10T18::35::57'),
('2022-06-10T18::35::57'))
select to_date('2022-06-10T18::35::57') from date_cte;
100040 (22007): Date '2022-06-10T18::35::57' is not recognized
Using timestamp will not work too due to '::' in time portion
with date_cte(created_at) as
(select * from values
('2022-06-10T18::35::57'),
('2022-06-10T18::35::57'))
select to_timestamp('2022-06-10T18::35::57','yyyy-mm-dd"T"hh24:mi:ss') from date_cte;
100096 (22007): Can't parse '2022-06-10T18::35::57' as timestamp with format 'yyyy-mm-dd"T"hh24:mi:ss'
Below takes care of both -
with date_cte(created_at) as
(select * from values
('2022-06-10T18::35::57'),
('2022-06-10T18::35::57'))
select to_timestamp('2022-06-10T18::35::57','YYYY-MM-DD"T"HH24::MI::SS') from date_cte;
TO_TIMESTAMP('2022-06-10T18::35::57','YYYY-MM-DD"T"HH24::MI::SS')
2022-06-10 18:35:57.000
2022-06-10 18:35:57.000
Now to compare - just convert in desired format using to_char -
with date_cte(created_at) as
(select * from values
('2022-06-10T18::35::57'),
('2022-06-10T18::35::57'))
select * from date_cte
where to_char(to_timestamp('2022-06-10T18::35::57','YYYY-MM-DD"T"HH24::MI::SS'),'yyyy-mm-dd')='2022-06-10';
CREATED_AT
2022-06-10T18::35::57
2022-06-10T18::35::57
One possible way is to do this:
SELECT *
FROM table
WHERE CAST(SUBSTRING(created_at, 0, 11) as date) = '2022-06-10'

Calculate number of specific days between dates in Snowflake

I am looking for some guidance on finding number of occurrences of lets say Monday and Wednesday between two dates Date1 and Date2 inclusive of the two dates in Snowflake. Any Suggestions?
A standard practice is to build a calendar table: either as pernament table or inlined view.
CREATE TABLE calendar
AS
SELECT DATEADD(day, ROW_NUMBER() OVER(ORDER BY seq8()), '1999-12-31'::DATE) AS d,
DAYOFWEEK(d) AS day_of_week,
DAYNAME(d) AS day_name
-- month/quarter/year/...
FROM TABLE(GENERATOR(ROWCOUNT => 365*100));
Then:
SELECT c.day_name, COUNT(*) AS cnt
FROM calendar c
WHERE c.d BETWEEN '<date_1>' AND '<date_2>'
AND c.day_of_week IN (1,3)
GROUP BY c.day_name;
Notes: day of week depeneds on parameter WEEK_START.
Lukasz's table solution is quite neat, but I will try the JS version:
// not sure the best name to have here
create or replace function num_of_days_in_between(
day_nums varchar(255),
start_date varchar(10),
end_date varchar(10)
)
RETURNS string
LANGUAGE JAVASCRIPT
AS $$
// perform some validations first on parameters
var s = new Date(START_DATE);
var e = new Date(END_DATE);
var split = DAY_NUMS.split(",");
var count = 0;
var d = s;
// go through each day and check if the
// current day is in the days asked
while (d.getTime() <= e.getTime()) {
// split array contains strings, so we need to
// force getDay() value to be string as well,
// otherwise includes() will not find it
if(split.includes(d.getDay()+"")) {
count++;
}
// advance to the next day
d = new Date(d.getTime() + 86400000);
}
return count;
$$;
-- Monday and Wednesday
select num_of_days_in_between('1,3', '2021-10-01', '2021-11-01'); -- 9
-- Tuesday
select num_of_days_in_between('2', '2021-10-01', '2021-11-01'); -- 4
Note that in JS, days start from Sunday with index of 0, refer to Date.getDay().

Why it is returning the date which is not between the range?

I want to only display the data in between 15 to 23 May 2019. But why it is also returning the data which is not between the date range?
Below is my query
SELECT Appointment_ID,
WO_DespatchName, Despatch_Name AS WO_selectDespatchName,
FORMAT(Appointment_DateTime, 'dd/MMM/yyyy hh:mm tt') AS Appointment_DateTime,
FORMAT(Appointment_ProposalSent, 'dd/MMM/yyyy') AS Appointment_ProposalSent,
WO_MaidName, Maid_Name AS WO_selectMaidName,
Appointment_Location, Appointment_FaceToFace, Appointment_Service, Appointment_Remarks, WO_Duration,
Appointment_ContactID, Contact_Name AS Appointment_selectContactID
FROM Appointments A
LEFT JOIN Despatch ON Despatch_ID = WO_DespatchName
LEFT JOIN CustomerDetails ON Contact_ID = Appointment_ContactID
LEFT JOIN Maid ON Maid_ID = WO_MaidName
WHERE FORMAT(Appointment_DateTime, 'dd/MM/yyyy') BETWEEN '15/05/2019' AND '23/05/2019'
AND (A.IsDelete = 0 OR A.IsDelete IS NULL)
ORDER BY CONVERT(DateTime, Appointment_DateTime,101) ASC
The output that I get is this https://drive.google.com/file/d/1VnrSET1V1eoFvEUUtRwXtQmKGWamURgV/view?usp=sharing
You are comparing texts, not dates. So it will return any row where date converted to string starts between 15 and 23.
You need to use date datatype in your comparison:
WHERE Appointment_DateTime >= CAST('20190515' AS date) AND Appointment_DateTime < CAST('20190524' AS date)
Please notice I added one day to the end range, so 05/23/2019 11:59:59.9... PM still will be accepted. CAST as date is not necessary, but improves readability.
The problem is in your where clause. Since your Appointment_DateTime is in datetime format. I am expecting that this column has value type datetime.
Now come to your query, '23/05/2019' is simple string, so unable to compare this as datetime. First you need to convert your from and to date into datetime format.
Please try this (if only date matching is your concern):
SELECT Appointment_ID,
WO_DespatchName, Despatch_Name AS WO_selectDespatchName,
FORMAT(Appointment_DateTime, 'dd/MMM/yyyy hh:mm tt') AS Appointment_DateTime,
FORMAT(Appointment_ProposalSent, 'dd/MMM/yyyy') AS Appointment_ProposalSent,
WO_MaidName, Maid_Name AS WO_selectMaidName,
Appointment_Location, Appointment_FaceToFace, Appointment_Service, Appointment_Remarks, WO_Duration,
Appointment_ContactID, Contact_Name AS Appointment_selectContactID
FROM Appointments A
LEFT JOIN Despatch ON Despatch_ID = WO_DespatchName
LEFT JOIN CustomerDetails ON Contact_ID = Appointment_ContactID
LEFT JOIN Maid ON Maid_ID = WO_MaidName
WHERE FORMAT(Appointment_DateTime, 'dd/MM/yyyy') BETWEEN FORMAT('15/05/2019', 'dd/MM/yyyy') AND FORMAT('23/05/2019', 'dd/MM/yyyy')
AND (A.IsDelete = 0 OR A.IsDelete IS NULL)
ORDER BY CONVERT(DateTime, Appointment_DateTime,101) ASC
Or you may try convert to convert your string into datetime format.
Feel free to ask for any further confusion.

how to query where date with time = date without time in ms sql

I want to do a query with dates this is my sample tsql:
select * from Bookings where StartTime = '2/15/2014'
the starttime has value '2/15/2014 12:00:00 AM'
when I query where StartTime = date with no time the result is 0
Anybody can help how to do this?
thanks
Try like this
SELECT * FROM Bookings WHERE Convert(VARCHAR(10),StartTime,101) = Convert(Varchar(10),'2/15/2014',101)
If you are using SQL SERVER 2012
Try this
SELECT * FROM Bookings WHERE FORMAT(StartTime,'M/dd/yyyy') = FORMAT('2/15/2014','M/dd/yyyy')
SQL FORMAT
The best way to do this is with a simple comparison:
select *
from Bookings
where StartTime >= cast('2014-02-15' as date) and StartTime < cast('2014-02-14' as date);
This is the safest method of comparison, because it will take advantage of an index on StartTime. This property is called "sargability".
In SQL Server, casting to a date should also be sargable, so you could also do:
select *
from Bookings
where cast(StartTime as date) = cast('2014-02-15' as date) ;
'2/15/2014' can be interpreted different depending on your locale. Try using the ISO date literal '2014-02-15', which is independent of the locale.
select * from Bookings where StartTime = '2014-02-15'
Or if StartTime includes hours:
select * from Bookings where StartTime >= '2014-02-15' and StartTime < '2014-02'16'
I believe you could also do this:
select * from Bookings where StartTime::date = '2014-2-15'

Resources