Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the sqlite equivalents of MySQL's INTERVAL and UTC_TIMESTAMP?

Tags:

sqlite

mysql

What are the sqlite equivalents of INTERVAL and UTC_TIMESTAMP? For example, imagine you were "porting" the following SQL from MySQL to sqlite:

SELECT mumble
  FROM blah
 WHERE blah.heart_beat_time > utc_timestamp() - INTERVAL 600 SECOND;
like image 818
Jacob Gabrielson Avatar asked Jul 08 '09 23:07

Jacob Gabrielson


People also ask

What is Strftime in SQL?

The strftime() function returns a formatted string by taking a timestring (with modifiers) and formating it according to format , a printf() style format specification. If any of the parameters are in an incorrect or illegal format, a NULL is returned.

How do I find the difference between two dates in SQLite?

To calculate the difference between the timestamps in SQLite, use the JULIANDAY() function for both timestamps, then subtract one from the other. This way, you get the difference in days. The integer part of the difference is the number of full days, and the decimal part represents a partial day.

What is the datetime format in SQLite?

The datetime() function returns the date and time as text in their same formats: YYYY-MM-DD HH:MM:SS.

Does an SQLite database support date time objects?

Date and Time Datatype. 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: TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.


2 Answers

datetime('now') provides you the current date and time in UTC, so is the SQLite equivalent of MySQL's UTC_TIMESTAMP().

It may also be useful to know that given a date and time string, datetime can convert it from localtime into UTC, using datetime('2011-09-25 18:18', 'utc').

You can also use the datetime() function to apply modifiers such as '+1 day', 'start of month', '- 10 years' and many more.

Therefore, your example would look like this in SQLite:

SELECT mumble
  FROM blah
 WHERE blah.heart_beat_time > datetime('now', '-600 seconds');

You can find more of the modifiers on the SQLite Date and Time Functions page.

like image 69
Rikki Avatar answered Oct 06 '22 23:10

Rikki


There's no native timestamp support in sqlite.

I've used plain old (64-bit) integers as timestamps, representing either micro- or milliseconds since an epoch.

Therefore, assuming milliseconds:

SELECT mumble
  FROM blah
WHERE blah.heart_beat_time_millis > ? - 600*1000;

and bind system time in milliseconds to the first param.

like image 2
laalto Avatar answered Oct 06 '22 21:10

laalto