Sqlite get records by hour - android

I want to make a query to get records between specified hours. For example, i want to get all records between 00:00 and 01:00 for all days. So, the date does not matter but hours. How to do that?
I have done this, but it only return for certain dates.
Select name from my_table where date_column> beginning and date_column< end
Here beginning and end are in millisecond. Also my date_column is stored in millisecond format.

Use strftime():
Select name
from my_table
where strftime('%H', date_column) = '00';
This just checks the hour. You could use '%H:%M:%S' if you wanted more granularity.
EDIT:
You do not have a date time value. You have something else. It looks like a Unix epoch time measured in milliseconds rather than seconds. If so, the following should work:
Select name, datetime(date_column/1000, 'unixepoch')
from my_table
where strftime('%H', datetime(date_column/1000, 'unixepoch')) = '19';
However, none of the times are at hour 3. You may need to convert using your localtime.

Related

Android working with dates and SQLite

I am trying to create a simple reminder app. Im just logically thinking about the process. Basically I want to be able to choose a DAY and time e.g Monday 15:00, this will trigger EVERY Monday 15:00 until it gets deleted from database. Having said that example I have questions to accomplish this process.
How will I store DAY and TIME, what type, do I need different columns in my table?
How can I compare real time DAY to current DAY, so if its Monday real time it will return ONLY Monday reminders? is this possible?
Will I need to primarly focus using calendar?
As documentation says:
SQLite does not have a storage class set aside for storing dates
and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values.
You can store date and time in the TEXT type of field in the following format:
YYYY-MM-DD HH:MM:SS.SSS
and then use built-in date & time functions of SQLite to filter your records.
Another option is to store date & time as a time-stamp in milliseconds and write proper queries for selecting data or use Joda library for filtering or date & time transformation, but probably such solution would be less efficient and less convenient than first option.
Using integer column is the easiest solution.
Just store the date in millisecond (Calendar.getTimeInMillis()) and your good to go.
Then you just have to search on that integer to find the correct event in your database :
String selectQuery = "SELECT whateveryouneed FROM events WHERE date_event > ?";
Cursor c = db.rawQuery(selectQuery, new String[] { String.valueOf(calendar.getTimeInMillis())});
...
if you need to find all the event for a day , you just have to find the limits of the day in millisecond and make a query according to those limits

Query unique date to cursor

In my database dates is stored in miliseconds as string. How to query unique dates considering only month and day and count how many date share same day?
Divide by 1000 to get seconds, then use the unixepoch modifier to get date, and use strftime to output only the year and month:
SELECT strftime('%Y-%m', DateMillis / 1000, 'unixepoch'),
COUNT(*)
FROM MyTable
GROUP BY 1
If you want to store a date, use date type. Sqlite may not have it. But please, do not use it as string! I would suggest you to store integer to store miliseconds sice epoch. Use bindLong() and such. Unfortunately, you have to make some computations yourself in code. Just compute first and last milisecond of each day. Then you would be able to use WHERE timestamp BETWEEN first_day_milisecond AND last_day_milisecond, using even indexes.
You can select min and max of timestamp to try only days between them.
If you need to do this frequently or over a lot of data, I suggest to store date in multiple columns as integers for year, month, day. Depends on what you have to do with time, miliseconds since midnight. Or more columns of hour, minute, second and miliseconds.
I think it is much easier to format string date from bunch of numbers than parsing those numbers from a string. Definitely easier to compare them inside database.

SQLite use year with date functions in where clause and group by

I am keeping date time values(Unix timestamps) in a "NUMERIC" format in SQLite table, the value is calculated through Java Date function:
new Date().getTime();
The values look like proper date/time when I load these in an Android program, but when I try to experiment with queries through SQLite data browser 2 beta the results are awkward. Numeric values are given below:
1391313058888
1391313104336
1391313175752
When I try to apply date function the SQLite data browser shows following for all three rows:
-1413-03-01 13:07:12
My query is
SELECT date(trxDateTime, 'unixepoch') from trx_log
I was trying to figure out how to get correct date values in the first place, once I got those then I believe I could figure a way to use it in where clause or group by.
Basically I am trying to show totals sales by year. Any help will be appreciated.
Your times are in milliseconds. Just convert them to seconds, and you'll be fine:
SELECT date(trxDateTime / 1000, 'unixepoch') from trx_log

Group resulting rows by hour of the day sqllite android

There are entries in a table containing 2 columns (integerdata, time). Time is stored in TEXT and is of format HH:MM, which is one of the standard format ( according to sqllite documentation). 'integerdata' is some integer. I am looking to obtain row contents grouped by hour of the day, with integerdata as AVG(integerdata) for each hour. Eg rows:
(10, 10:01)
(2, 10:25)
(5, 11:01)
(9, 11:25)
I wish to have the output like:
6, 10:00
7, 11:00
One novice and horrible way is to give a query for each hour range(making 24 queries). Something like:
SELECT AVG(integerdata) from table WHERE time BETWEEN 'time1' AND 'time2'
//time1 and time2 can vary between 10:00 to 11:00; then 11:00 to 12:00 ...
Second way might be to use GROUP BY Clause, but I am not sure how. I googled and also tried to look on some answers on stackoverflow but was of no help. I would really appreciate any contribution. Thanks!
I am looking to obtain row contents grouped by hour of the day, with
integerdata as AVG(integerdata) for each hour.
Here is my first idea. Since your time is still TEXT, you can use substr() function to get only hour from your time column and then you can use this substring in GROUP BY clause.
Select AVG(integerdata), SUBSTR(time, 0, 3) as gt from Table group by gt;
I assume that your time format is HH:MM so in this case SUBSTR(time, 0, 3) returns only hours and now you can start grouping by hours.
It returns: 10, 11, 12, ...

Get data from sqlite database per day DATE TIME

I have a sqlite database. I have three columns:_id, date, value.
I now want to extract a count of the _id:s depending on the day in the date, and calculate an average of the int value. This is for an Android app.
So I want to "select the day in date and for each day ( for sixty days), count how many _id:s there are for this day. Finally calculate the average of value.
I guess it is something like :
"SELECT DATE('now' 'days[i]') as date, COUNT(_id) as count, AVG(value) as vl FROM v_efforts WHERE DATE(v_efforts.date) = DATE('now' 'days[i]')";
But I can't get the 'days[i]' to work. I don't know how i can get this value to increase to sixty, and then how I can store the count and vl for each of these sixty days.
THanks a lot!
You'll want to use a GROUP BY expression to aggregate the entries by date. It's not quite clear whether you're looking for the last 60 days of entries in the database, or the entries from the last 60 real days (which would only be the same if you can assume that there are entries every day).
For the former (last 60 days which had database entries), you can use a LIMIT clause:
SELECT date,COUNT(_id),AVG(value) FROM v_efforts GROUP BY date ORDER BY date DESC LIMIT 60;
For the latter (last 60 real days), you can use WHERE:
SELECT date,COUNT(_id),AVG(value) FROM v_efforts WHERE date>DATE('now','-60 days') GROUP BY date ORDER BY date DESC;
The docs for Version 3 are pretty decent:
http://www.sqlite.org/lang_datefunc.html
I would look at the block that deals with the built in date time functions. Since SQLite doesn't support an actual date datetype:
Compute the current date:
SELECT date('now');
Compute the last day of the current month:
SELECT date('now','start of month','+1
month','-1 day');
Compute the date and time given a unix timestamp 1092941466.
SELECT datetime(1092941466,
'unixepoch');
Compute the date and time given a unix timestamp 1092941466, and compensate for your local timezone.
SELECT datetime(1092941466,
'unixepoch', 'localtime');
Compute the current unix timestamp.
SELECT strftime('%s','now');
Compute the number of days since the signing of the US Declaration of Independence.
SELECT julianday('now') -
julianday('1776-07-04');
Compute the number of seconds since a particular moment in 2004:
SELECT strftime('%s','now') -
strftime('%s','2004-01-01 02:34:56');
Compute the date of the first Tuesday in October for the current year.
SELECT date('now','start of year','+9
months','weekday 2');
Compute the time since the unix epoch in seconds (like strftime('%s','now') except includes fractional part):
SELECT (julianday('now') -
2440587.5)*86400.0;

Categories

Resources