Select rows which date (epoch) field equals a specific year [duplicate] - sql

I store date from Calendar.getTimeInMilliseconds() in SQLite DB.
I need to mark first rows by every month in SELECT statement, so I need convert time in milliseconds into any date format using SQLite function only. How can I avoid this?

One of SQLite's supported date/time formats is Unix timestamps, i.e., seconds since 1970.
To convert milliseconds to that, just divide by 1000.
Then use some date/time function to get the year and the month:
SELECT strftime('%Y-%m', MillisField / 1000, 'unixepoch') FROM MyTable

Datetime expects epochtime, which is in number of seconds while you are passing in milliseconds. Convert to seconds & apply.
SELECT datetime(1346142933585/1000, 'unixepoch');
Can verify this from this fiddle
http://sqlfiddle.com/#!5/d41d8/223

Do you need to avoid milliseconds to date conversion or function to convert milliseconds to date?
Since sqlite date functions work with seconds, then you can try to
convert milliseconds in your query, like this
select date(milliscolumn/1000,'unixepoch','localtime') from table1
convert millis to seconds before saving it to db, and then use date function in sql query

Related

SQLite How can I select data between 2 date with time included

I have seperate date and time columns in my table. Date as mm/dd/yyyy, time as hh:mm but i can change the format. I want to list data between 2 date/time. How can I do that?
select * from testtable where date >= '01/10/2022' AND date <= '01/10/2023' AND time >= '13:45' AND time <= '15:50'
I wrote it but of course it doesn't work like what i expected.
The best fix and really the only one you want here would be to start storing your timestamps in a sortable ISO format yyyy-mm-dd hh:ii:ss. Then, use this query:
SELECT *
FROM testtable
WHERE date BETWEEN '2022-01-10 13:45:00' AND '2023-01-10 15:50:00';
The thing to realize here is that SQLite does not actually have a date column type. Rather, you always store your dates/timestamps as text, and therefore it is crucial to use an ISO sortable format as shown above.
If your target is sqlite, it lacks complex timestamp types. But you have another option here. You can store that as unix timestamp, it is an integer representing the number of seconds offset from the epoch which is 1970-01-01 00:00:00 UTC. The table format would then be:
CREATE TABLE testtable (
date INTEGER
);
You can the use the unixepoch function to translate a string representation to that unix timestamp format. To insert a new date, you would use:
INSERT INTO testtable (date) VALUES (unixepoch('2023-01-11T11:30:00+01:00'))
Finding a matching row is now as easy to compare integers together. You can convert the datetime representation to unix timestamp at the application level, most programming environments provide such time utility functions/library. Or can still use the unixepoch function from sqlite for your where clause.
SELECT * FROM testtable
WHERE date >= unixepoch('2022-10-01T13:45:00Z')
AND date <= unixepoch('2023-10-01T15:50:00Z')
The final Z indicates an UTC time zone but you can adjust that with another +HH:00 extenstion instead which reflect the offset from utc of your datetime representation.

time difference in sql Oracle

I need to know a difference between start time and end time. Both are DATETIME fields, I tried to use "-" and DATADIFF.
I already tried using DATADIFF and simple subtraction converting the field to just time.
(to_date(Fim_Hora,'HH24:MI') - to_date(Inicio_Hora,'HH24:MI')) AS Diferenca
DATADIFF(MIN,Fim_Hora,Inicio_Hora)
I need to know the time in minutes for use as parameters.
Oracle does not have a time data type. Usually, subtraction works well enough:
select (end_time - start_time) as diff
You may need to convert to a string if you want it formatted in a particular way.
In Oracle, you can directly substract dates, it returns the difference between the dates in days. To get the difference in minutes, you can multiply the result by 24 (hours per days) and 60 (minutes per hour):
(Fim_Hora - Inicio_Hora) * 24 * 60 diff_minutes
This assumes that both Fim_Hora and Inicio_Hora are of datatype DATE.

SQL Solr query Convert date to

I'm interested in the question: how to convert date to number in millis with Solr SQL? Is it possible?
You have to use Function Queries (https://lucene.apache.org/solr/guide/6_6/function-queries.html)
For example: in the field returned by your query, just insert ms(2000-01-01T00:00:00Z) or ms(mydatefield)
http://localhost:8983/solr/job/select?fl=ms(2000-01-01T00:00:00Z)&indent=on&q=:&wt=json
result: 946684800000
Obs2: Dates are relative to midnight, January 1, 1970 UTC (you can use function queries and calculate milliseconds between to dates)
Obs1: your date field type (mydatefield in the above example) should be a TrieDateField

Converting only time to unixtimestamp in Hive

I have a column eventtime that only stores the time of day as string. Eg:
0445AM - means 04:45 AM. I am using the below query to convert to UNIX timestamp.
select unix_timestamp(eventtime,'hhmmaa'),eventtime from data_raw limit 10;
This seems to work fine for test data. I always thought unixtimestamp is a combination of date and time while here I only have the time. My question is what date does it consider while executing the above function? The timestamps seem to be quite small.
Unix timestamp is the bigint number of seconds from Unix epoch (1970-01-01 00:00:00 UTC). The unix time stamp is a way to track time as a running total of seconds.
select unix_timestamp('0445AM','hhmmaa') as unixtimestamp
Returns
17100
And this is exactly 4hrs, 45min converted to seconds.
select 4*60*60 + 45*60
returns 17100
And to convert it back use from_unixtime function
select from_unixtime (17100,'hhmmaa')
returns:
0445AM
If you convert using format including date, you will see it assumes the date is 1970-01-01
select from_unixtime (17100,'yyyy-MM-dd hhmmaa')
returns:
1970-01-01 0445AM
See Hive functions dosc here.
Also there is very useful site about Unix timestamp

SQLite Current Timestamp with Milliseconds?

I am storing a timestamp field in a SQLite3 column as TIMESTAMP DATETIME DEFAULT CURRENT_TIMESTAMP and I was wondering if there was any way for it to include milliseconds in the timestamp as well?
Instead of CURRENT_TIMESTAMP, use (STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')) so that your column definition become:
TIMESTAMP DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW'))
For example:
CREATE TABLE IF NOT EXISTS event
(when_ts DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')));
To get number of milliseconds since epoch you can use julianday() with some additional calculations:
-- Julian time to Epoch MS
SELECT CAST((julianday('now') - 2440587.5)*86400000 AS INTEGER);
The following method doesn't require any multiplies or divides and should always produce the correct result, as multiple calls to get 'now' in a single query should always return the same result:
SELECT strftime('%s','now') || substr(strftime('%f','now'),4);
The generates the number of seconds and concatenates it to the milliseconds part from the current second+millisecond.
Here's a query that will generate a timestamp as a string with milliseconds:
select strftime("%Y-%m-%d %H:%M:%f", "now");
If you're really bent on using a numeric representation, you could use:
select julianday("now");
The accepted answer only gives you UTC. If you need a local time instead of UTC, use this:
strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime')