How to get previous day via SQLite in Swift - sqlite

I have a sqlite table with a number of dates. I would like to execute a query to select those records where the Date is the previous date. I have tried the following but it doesn't work:
SELECT SUM(Amount) AS TOTAL FROM (SpentAmount) Where Date ='\(Date().yesterday)'"
and output is : '2018-07-02 05:43:16 +0000'
But I want only date and this format: '02-07-2018'.
And I m trying This : SELECT SUM(Amount) AS TOTAL FROM SpentAmount WHERE Date = DATE('now', '-1 days');
but this Query give me no result
This is my database Database
but when i execute the query then give me this result

If you want to target yesterday (i.e. the date before today), then use DATE('now', '-1 days'):
SELECT SUM(Amount) AS TOTAL
FROM SpentAmount
WHERE Date = STRFTIME('%d.%m.%Y', DATE('now', '-1 days'));
As a general comment, your current date format is very non ideal. It will be very hard to sort your table by date. Instead, you should always store your date information in ISO format with SQLite, i.e. use 2018-07-02, not 02-07-2018.

Related

sqlite3 (on qnx): How to get data from a table x mins from the latest time?

I have an sqlite3 database with the following schema:
CREATE TABLE sysTime (time date, source TEXT, destination TEXT, action TEXT, status TEXT, string TEXT, rogue_id TEXT);
I want to query the db to return only rows inserted in the last x minutes(or hours or days) with respect to the last entered time in the db.
Example: If I want to query the db to return rows inserted in the past 1 day (or 24 hrs), it should only return the last row (i.e 2018-05-09T17:24:25.243 - 24 hours)
I tried using max(time) along with Datetime and it didn't really work:
I found this example online --> select count(*) from syslog where time >= Datetime('now','-7 days'); and modified it to what I wanted to as below:
select * from sysTime where time >=Datetime('select max(time) from syslog','-1 day');
but sqlite3 doesn't return any rows. Tried couple of other sql commands to no avail. Any help is appreciated.
Subqueries are written inside parentheses:
SELECT * FROM sysTime
WHERE time >= datetime((SELECT max(time) FROM syslog),
'-1 day');

how to apply strftime on localtime

I want to get the day of the month from a datetime column in my Sqlite database. I could use simply
select strftime('%d',myColumn) from myTable
But the values are stored in UTC in the database and i want to get the dates based on the localtime. So i can do the below to get the localtime.
select date(myColumn, 'localtime') from myTable
Now how do i do both these operations together? The only way i can think is by doing inner query with the date() and outer query with strftime(). Is there another way?
The documentation says that modifiers like localtime are used with all date and time functions:
SELECT strftime('%d', myColumn, 'localtime') FROM myTable

sqlite, selecting number of unique values for each month

I am relatively new to sqlite and I am trying to count the number of unique stores each month in my table. My query looks like this:
SELECT COUNT(DISTINCT Store_Num) FROM 'heroes' WHERE strftime('%y-%m', Date)='2005-01';
however it is returning 0 each time. I think it may have to do with my strftime syntax, but I have gone through the documentation and am unable to figure it out.
Thanks!
Uppercase "Y". strftime('%Y-%m', Date)
sqlite> select strftime('%Y-%m', dt) from test;
2014-01

Change sqlite to use machine's TZ and not GMT [duplicate]

I have a sqlite (v3) table with this column definition:
"timestamp" DATETIME DEFAULT CURRENT_TIMESTAMP
The server that this database lives on is in the CST time zone. When I insert into my table without including the timestamp column, sqlite automatically populates that field with the current timestamp in GMT, not CST.
Is there a way to modify my insert statement to force the stored timestamp to be in CST? On the other hand, it is probably better to store it in GMT (in case the database gets moved to a different timezone, for example), so is there a way I can modify my select SQL to convert the stored timestamp to CST when I extract it from the table?
I found on the sqlite documentation (https://www.sqlite.org/lang_datefunc.html) this text:
Compute the date and time given a unix
timestamp 1092941466, and compensate
for your local timezone.
SELECT datetime(1092941466, 'unixepoch', 'localtime');
That didn't look like it fit my needs, so I tried changing the "datetime" function around a bit, and wound up with this:
select datetime(timestamp, 'localtime')
That seems to work - is that the correct way to convert for your timezone, or is there a better way to do this?
simply use local time as the default:
CREATE TABLE whatever(
....
timestamp DATE DEFAULT (datetime('now','localtime')),
...
);
You should, as a rule, leave timestamps in the database in GMT, and only convert them to/from local time on input/output, when you can convert them to the user's (not server's) local timestamp.
It would be nice if you could do the following:
SELECT DATETIME(col, 'PDT')
...to output the timestamp for a user on Pacific Daylight Time. Unfortunately, that doesn't work. According to this SQLite tutorial, however (scroll down to "Other Date and Time Commands"), you can ask for the time, and then apply an offset (in hours) at the same time. So, if you do know the user's timezone offset, you're good.
Doesn't deal with daylight saving rules, though...
In the (admitted rare) case that a local datatime is wanted (I, for example, store local time in one of my database since all I care is what time in the day is was and I don't keep track of where I was in term of time zones...), you can define the column as
"timestamp" TEXT DEFAULT (strftime('%Y-%m-%dT%H:%M','now', 'localtime'))
The %Y-%m-%dT%H:%M part is of course optional; it is just how I like my time to be stored. [Also, if my impression is correct, there is no "DATETIME" datatype in sqlite, so it does not really matter whether TEXT or DATETIME is used as data type in column declaration.]
When having a column defined with "NOT NULL DEFAULT CURRENT_TIMESTAMP," inserted records will always get set with UTC/GMT time.
Here's what I did to avoid having to include the time in my INSERT/UPDATE statements:
--Create a table having a CURRENT_TIMESTAMP:
CREATE TABLE FOOBAR (
RECORD_NO INTEGER NOT NULL,
TO_STORE INTEGER,
UPC CHAR(30),
QTY DECIMAL(15,4),
EID CHAR(16),
RECORD_TIME NOT NULL DEFAULT CURRENT_TIMESTAMP)
--Create before update and after insert triggers:
CREATE TRIGGER UPDATE_FOOBAR BEFORE UPDATE ON FOOBAR
BEGIN
UPDATE FOOBAR SET record_time = datetime('now', 'localtime')
WHERE rowid = new.rowid;
END
CREATE TRIGGER INSERT_FOOBAR AFTER INSERT ON FOOBAR
BEGIN
UPDATE FOOBAR SET record_time = datetime('now', 'localtime')
WHERE rowid = new.rowid;
END
Test to see if it works...
--INSERT a couple records into the table:
INSERT INTO foobar (RECORD_NO, TO_STORE, UPC, PRICE, EID)
VALUES (0, 1, 'xyz1', 31, '777')
INSERT INTO foobar (RECORD_NO, TO_STORE, UPC, PRICE, EID)
VALUES (1, 1, 'xyz2', 32, '777')
--UPDATE one of the records:
UPDATE foobar SET price = 29 WHERE upc = 'xyz2'
--Check the results:
SELECT * FROM foobar
Hope that helps.
SELECT datetime(CURRENT_TIMESTAMP, 'localtime')
SELECT datetime('now', 'localtime');
Time ( 'now', 'localtime' ) and Date ( 'now', 'localtime' ) works.
You can also just convert the time column to a timestamp by using strftime():
SELECT strftime('%s', timestamp) as timestamp FROM ... ;
Gives you:
1454521888
'timestamp' table column can be a text field even, using the current_timestamp as DEFAULT.
Without strftime:
SELECT timestamp FROM ... ;
Gives you:
2016-02-03 17:51:28
I think this might help.
SELECT datetime(strftime('%s','now'), 'unixepoch', 'localtime');
The current time, in your machine's timezone:
select time(time(), 'localtime');
As per http://www.sqlite.org/lang_datefunc.html

How to structure my query in sqlite?

I would like to retrieve today's data. At the moment I have something like SELECT * FROM myTable WHERE timeStamp>DATETIME('NOW','-1 DAY') but this gives me results from now to 24hrs back, not just today (i.e. no matter how many hours have passed since 00:00). Using the same logic I want to retrieve data for just yesterday, and for the this week.
[EDIT]
By the term this week i mean.. if today is Thursday, i want to show results from monday or Sunday (it doesnt matter) upto now.
Instead of timeStamp > DATETIME('now') use timeStamp >= DATE('now').
For since yesterday you can use DATE('now', '-1 day').
As for this week - it depends if you mean 7 days ago:
DATE('now', '-7 days')
Or if you mean since the beginning of the first day of this week:
DATE('now', 'weekday 0', '-7 days')

Resources