How to get the last date of the week in sqlite3? - sqlite

Let's say I have a column with values in the format of a datetime '2021-07-01 00:00:00.000', how do I get the last date of the week (Sunday) for any datetime such as this in sqlite3? The day of the last date of the week is a Sunday.
So the answer for this date would want something like 2021-07-04 or 2021/07/04 (removing the time part) which is the date of the Sunday for the week the date 2021-07-01 is belonging to.
I know how this can be done in sqlserver but I do not know how to do it in sqlite.
Could someone please assist me on this? Let me know if you need more clarification.
Here is my attempt on sqlserver, but i need to get the same result in sqlite
SELECT
somedate,
CONVERT(VARCHAR(10),DATEADD(DAY, 7 - DATEPART(WEEKDAY, [somedate]), [somedate]),111) AS Last_Date_Of_Week
FROM table
apparently i can't do this in sqlite because sqlite does not have an official datetime type.

Sqlite date and time functions consider Sunday to be the first day of the week, and have a weekday modifier to advance a given timestamp to the given day of the week (Using 0-based indexing from Sunday). So:
sqlite> SELECT date('2021-07-01 00:00:00.000', 'weekday 0');
date('2021-07-01 00:00:00.000', 'weekday 0')
--------------------------------------------
2021-07-04

Related

Negative dates in sqllite database

I am working locally with an sqllite DB. I have imported some records from teradata where there was a date field in the format of 'YYYY-MM-DD'. When i imported the records the date switched from a date to a number. I know this is a feature of sqllite and that one can access it via date(sqllite_date) when selecting it in a where clause.
My problem is that the dates now appear to be a bit odd. For example the year appears to be negative.
Is there anyway to recover this to the correct format?
Below is an example of converting a number in the database into a date
SELECT date(18386)
# -4662-03-28
SELECT datetime('now')
# 2021-02-11 10:41:52
SELECT date(sqllite_date) FROM mydb
# Returns -4662-03-28
# Should return 2020-05-04
I am very new to this area so apologies if this is a basic question. Thank you very much for your time
In SQLite you can store dates as TEXT, REAL or INTEGER.
It seems that you stored the dates in a column with INTEGER or REAL affinity.
In this case, if you use the function date(), it considers a value like 18386 as a Julian day, meaning the number of days since noon in Greenwich on November 24, 4714 B.C.
This is why date(18386) returns 4662-03-28B.C.
But I suspect that the date values that you have are the number of days since '1970-01-01'.
In this case, 18386 days after '1970-01-01' is '2020-05-04'.
So you can get the dates in the format YYYY-MM-DD if you add the value of your column as days to '1970-01-01':
SELECT date('1970-01-01', datecolumn || ' day') FROM tablename
Or by transforming your date values to seconds and treat them as UNIX time (the number of seconds since '1970-01-01 00:00:00 UTC'):
SELECT date(datecolumn * 24 * 3600, 'unixepoch') FROM tablename
Replace datecolumn with the name of your column.

SQlite is not querying output correctly

I have the following SQL statement, however it is including a date from October
The format from the csv line is 10/2/2017 17:32
Is it because my csv is incorrect?
Please help!
SELECT *
FROM MyTable
WHERE [Completion Status]= 'Incomplete'
AND [Curriculum Name] NOT LIKE '%Phishing Training%'
AND [Date Assigned] < date('now','-30 day')
ORDER BY [Employee Department]
You should probably change the format of the date in your CSV. I don't think SQLite recognizes that format. Once you do that the answer from Olivier should work.
https://www.sqlite.org/lang_datefunc.html
now (as of 17. Jan 2018) minus 30 days is 18. Dec 2017. Since you want [Date Assigned] < this date, i.e. before this date, a date from October is correct.
Did you intend to write
[Date Assigned] >= date('now','-30 day')
i.e. return entries at most 30 days old?
Also, according to the official SQLite documentation, you should store the date as YYYY-MM-DD HH:MM. See: Date And Time Functions.

SQLite return wrong week number for 2013?

I have a simple SQL for calculating week number in my reports on SQLite
SELECT STRFTIME('%W', 'date_column')
It was correct for 2009-2012. In 2013 I got always the wrong week number.
For example
SELECT STRFTIME('%W', '2012-02-28')
return '09' and this is correct.
SELECT STRFTIME('%W', '2013-02-28')
return '08' and this is wrong. We have the 9th week.
Is there something in SQLite date time functions that I don't understand? Or is it a bug of SQLite?
CL's answer works fine for OP's definition of "right", which is not quite the same as ISO definition. ISO week numbers are always in the range 1-53 (no week 0), and the last 3 days of a year may fall into Week 1 of the following year, just like the first 3 days may fall into Week 52 or 53 of the preceding year. To take these corner cases into account, you need to do something like:
SELECT
(strftime('%j', date(MyDate, '-3 days', 'weekday 4')) - 1) / 7 + 1 AS ISOWeekNumber
FROM MyTable;
As a side note, SQLite's Date and Time documentation does link to the POSIX strftime man page, which defines %W modifier as:
"week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0."
To convert from SQLite's undocumented week definition (first week is the week with the year's first Monday in it, or the week with 7 January in it) to the ISO week definition (first week is the week with the year's first Tuesday in it, or the week with 4 January in it), we let SQLite compute the week of the year's 4 January. If that is not one, we have to increase the week number:
SELECT strftime('%W', MyDate)
+ (1 - strftime('%W', strftime('%Y', MyDate) || '-01-04'))
FROM MyTable

SQLite : obtain current week

I'm trying to obtain the current week for date comparison in SQLite.
I have no problem for last month, last year, today, yesterday... but don't find the solution to have the current week.
I tried lot of things like:
SELECT tastings.* FROM tastings
WHERE (DATE(tastings.date) > DATE('now','weekday 1','+ 7 days'))
Can you help me ? Thanks.
This code gives you the week number where the first day of week is monday. It also works well for last and first weeks of the year.
strftime('%W', 'now', 'localtime', 'weekday 0', '-6 days')
I guess you want compare 2 date, Assume you have a table named _testTbl and have 3 column _id INTEGER, _name TEXT, _recordDate TEXT
you want name that record this week
you can use below code:
SELECT * FROM _testTbl
WHERE _recordDate > datetime('now', 'start of day', 'weekday 6', '-7 day')
note that this week start by saturday (sunday 0, monday 1, ..., saturday 7)
this t-sql means:
datetime is a sqlite date and time function.
first parameter is given time: 'now' means the current time.
second parameter take the time to start of day.
third parameter take time to the next weekday number (in this case, saturday).
fourth parameter take time to start of week
What is stored inside the tastings.date column? Note that SQLite does not have “timestamp” type affinity, so probably you store Text (some representation of the date) or integer (julian day, epoch…)
All time and date functions expect a valid time string and convert that time string to another string format. If tastings.date contains a week number then use:
AND cast(tastings.date AS TEXT) = strftime('%W','now')
This helps me to compare the 2 dates using the week of the year.
AND ( strftime('%W', tastings.date) = strftime('%W', 'now') )
Thanks you.

Correct date range in SQL

This has gotten me a little paranoid, but I'm retrieving a set of records that fall within a period of time, say, the period from the january 1, 2011 (starting at midnight) to march 31, 2011 (all records up to 11:59:59 PM)
I'm using the condition
t.logtime between to_date('2011-01-01', 'yyyy-mm-dd') and to_date('2011-03-31')
Note that logtime is a datetime field.
Does this reflect what I want? Or am I actually missing 24 hours less a second?
I could specify the time as well, but I was hoping I this could be done without it.
Yes, you are missing nearly all of the last day. There are various solutions; probablt the simplest is:
t.logtime >= to_date('2011-01-01', 'yyyy-mm-dd')
and t.logtime < to_date('2011-04-01', 'yyyy-mm-dd')
I'd use the ANSI date literal syntax too:
t.logtime >= date '2011-01-01'
and t.logtime < date '2011-04-01'
Another way is:
trunc(t.logtime) between date '2011-01-01' and date '2011-03-31'
but note that that can no longer use an index on logtime (though it can use an index on trunc(logtime)).

Resources