SaleDB Pro for $19.99 $99

SQLite timestamp: storing and querying dates

SQLite has no timestamp type. Store ISO 8601 text or Unix seconds in UTC, convert with datetime() and unixepoch(), and compare ranges, not function calls.

Quick answer

SQLite has no timestamp or date type. Store each timestamp as ISO 8601 text or as Unix seconds, keep it in UTC, and let the date functions convert it:

SQL
CREATE TABLE events (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP   -- '2026-12-04 09:30:00', UTC
);

SELECT name, datetime(created_at, 'localtime') AS local_time
FROM events
WHERE created_at >= '2026-12-01' AND created_at < '2027-01-01';

CURRENT_TIMESTAMP is UTC, not your local time. Most SQLite timestamp bugs come from forgetting that, or from mixing formats in one column.

Examples on this page were run on SQLite 3.43.2. The interactive editors run SQLite 3.45 in your browser. unixepoch() needs 3.38.0 or later, the subsec modifier needs 3.42.0, and timediff() needs 3.43.0.

There is no timestamp type

You can declare a column as DATETIME or TIMESTAMP and SQLite accepts it. It does not create a date type. Those names get NUMERIC affinity, which leads to an odd result: a numeric string is converted to an integer on the way in.

⚡
Loading SQL environment...
a|typeof(a)|b|typeof(b)
2026-12-04 09:30:00|text|1796342400|integer
2026-12-04|text|1796342400|integer

STRICT tables go further and reject the name:

Error: in prepare, unknown datatype for t.a: "DATETIME"

So pick a storage format on purpose. The SQLite data types guide covers affinity in more detail.

Three ways to store a timestamp

FormatExampleColumn typeGood for
ISO 8601 text'2026-12-04 09:30:00'TEXTReadable data, sorts correctly as text
Unix time1796342400INTEGERCompact, easy arithmetic, matches most application code
Julian day2461378.5REALFractional day arithmetic, rarely used

All three describe midnight UTC on 4 December 2026, and every date function accepts all three:

SQL
SELECT datetime('2026-12-04 00:00:00'),
       datetime(1796342400, 'unixepoch'),
       datetime(2461378.5);
2026-12-04 00:00:00|2026-12-04 00:00:00|2026-12-04 00:00:00

Note the 'unixepoch' modifier. Without it, SQLite reads a bare number as a Julian day, and datetime(1796342400) returns NULL. Since 3.38.0 the 'auto' modifier guesses between the two.

Text or integer? Use ISO 8601 text if people will read the database directly or you want CURRENT_TIMESTAMP defaults. Use integer Unix seconds if your application already works in epoch time. Either is fine. Mixing them is the mistake.

CURRENT_TIMESTAMP is UTC

CURRENT_TIMESTAMP, CURRENT_DATE, and CURRENT_TIME all return UTC, as text:

SQL
SELECT CURRENT_TIMESTAMP, CURRENT_DATE, CURRENT_TIME;
2026-09-30 09:03:33|2026-09-30|09:03:33

That ran on a machine set to British Summer Time, an hour ahead. Ask for local time explicitly with the 'localtime' modifier:

SQL
SELECT datetime('now') AS utc, datetime('now', 'localtime') AS local;
utc|local
2026-09-30 09:03:33|2026-09-30 10:03:33

'localtime' uses the time zone of the machine running SQLite, and it applies the right daylight saving offset for the date being converted. With TZ=America/New_York:

SQL
SELECT datetime('2026-12-04 15:00:00', 'localtime'),   -- 2026-12-04 10:00:00 (EST, UTC-5)
       datetime('2026-07-04 15:00:00', 'localtime'),   -- 2026-07-04 11:00:00 (EDT, UTC-4)
       datetime('2026-12-04 10:00:00', 'utc');         -- 2026-12-04 15:00:00

On a server, the machine's time zone is often UTC, so 'localtime' does nothing useful there. Store UTC and convert to the user's zone in the application.

Input strings with an offset are converted to UTC:

SQL
SELECT datetime('2026-12-04 09:30:00+05:30');   -- 2026-12-04 04:00:00

The date and time functions

FunctionReturnsExample output
date(t)YYYY-MM-DD2026-12-04
time(t)HH:MM:SS09:30:00
datetime(t)YYYY-MM-DD HH:MM:SS2026-12-04 09:30:00
julianday(t)Julian day as REAL2461378.895833...
unixepoch(t)Unix seconds as INTEGER (3.38.0+)1796376600
strftime(fmt, t)Custom format04/12/2026 09:30
timediff(a, b)Difference as text (3.43.0+)+0000-00-21 00:00:00.000

Each takes modifiers after the time value. Try some:

⚡
Loading SQL environment...

Useful strftime() codes: %Y year, %m month, %d day, %H hour, %M minute, %S seconds, %f seconds with milliseconds, %s Unix seconds, %w day of week (0 is Sunday), %j day of year, and %W week of year.

Differences between two timestamps

Subtract Unix seconds or Julian days:

SQL
SELECT (unixepoch('2026-12-04 18:00') - unixepoch('2026-12-04 09:30')) / 60 AS minutes,
       julianday('2026-12-25') - julianday('2026-12-04') AS days;
minutes|days
510|21.0

Milliseconds

CURRENT_TIMESTAMP stops at seconds. For milliseconds, use %f in strftime(), or the 'subsec' modifier on 3.42.0 and later:

SQL
SELECT strftime('%Y-%m-%dT%H:%M:%fZ', 'now') AS iso_ms,
       datetime('now', 'subsec')              AS subsec,
       unixepoch('now', 'subsec')             AS unix_ms;
iso_ms|subsec|unix_ms
2026-09-30T09:03:33.155Z|2026-09-30 09:03:33.155|1790759013.155

Default timestamps

CURRENT_TIMESTAMP works as a default on its own. Any function call needs parentheses around it:

SQL
CREATE TABLE events (
  id           INTEGER PRIMARY KEY,
  name         TEXT NOT NULL,
  created_at   TEXT    NOT NULL DEFAULT CURRENT_TIMESTAMP,
  created_unix INTEGER NOT NULL DEFAULT (unixepoch()),
  created_ms   TEXT    NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);

INSERT INTO events (name) VALUES ('signup');
SELECT * FROM events;
id|name|created_at|created_unix|created_ms
1|signup|2026-09-30 09:03:44|1790759024|2026-09-30T09:03:44.487Z

Leave out the parentheses and you get a syntax error:

SQL
CREATE TABLE t (a INTEGER DEFAULT unixepoch());
Error: in prepare, near "(": syntax error

An updated_at column

SQLite has no ON UPDATE CURRENT_TIMESTAMP like MySQL. Use a trigger:

SQL
CREATE TABLE posts (
  id         INTEGER PRIMARY KEY,
  title      TEXT NOT NULL,
  updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TRIGGER posts_touch AFTER UPDATE ON posts
FOR EACH ROW WHEN NEW.updated_at = OLD.updated_at
BEGIN
  UPDATE posts SET updated_at = CURRENT_TIMESTAMP WHERE id = NEW.id;
END;

The WHEN clause skips rows where the application set updated_at itself. It also keeps the trigger from looping if PRAGMA recursive_triggers is on.

Comparison traps

Text timestamps compare as strings. That works when every value has the same format, and fails when they do not.

Mixed separators

ISO 8601 allows a T or a space between the date and time. Put both in one column and comparisons break, because T sorts after a space:

⚡
Loading SQL environment...

The first query returns only 2026-12-04 09:30:00 and misses 2026-12-04T08:00:00Z. The second returns both. The fix inside the query costs you the index (see below), so fix the data instead: pick one format and convert on write.

Comparing a timestamp to a date

'2026-12-04 09:30:00' does not equal '2026-12-04', and BETWEEN '2026-12-04' AND '2026-12-04' matches nothing with a time part. Use a half-open range:

SQL
SELECT count(*) FROM logins WHERE at = '2026-12-04';                               -- 0
SELECT count(*) FROM logins WHERE at >= '2026-12-04' AND at < '2026-12-05';        -- 3

Integers and text in one column

SQLite sorts every integer before every text value. If a column holds both, a numeric comparison matches the text rows too:

SQL
CREATE TABLE mixed (at);
INSERT INTO mixed VALUES (1796342400), ('2026-12-04 09:30:00');

SELECT at, typeof(at) FROM mixed WHERE at > 1700000000;
1796342400|integer
2026-12-04 09:30:00|text

Check a suspect column with SELECT typeof(at), count(*) FROM t GROUP BY 1.

Invalid dates

The date functions return NULL for input they cannot parse, such as '2026-13-01', '04/12/2026', or '2026-12-4' (the day needs two digits). They do not validate day numbers, though: date('2026-02-30') returns 2026-02-30, and adding a modifier rolls it forward, so date('2026-02-30', '+0 days') returns 2026-03-02. Validate dates in the application or with a CHECK constraint.

Indexing timestamp columns

Wrapping an indexed column in a function hides it from the index:

SQL
CREATE INDEX orders_created_at ON orders(created_at);

EXPLAIN QUERY PLAN SELECT * FROM orders WHERE date(created_at) = '2026-12-04';
QUERY PLAN
`--SCAN orders

Rewrite it as a range on the raw column and the index is used:

SQL
EXPLAIN QUERY PLAN
SELECT * FROM orders WHERE created_at >= '2026-12-04' AND created_at < '2026-12-05';
QUERY PLAN
`--SEARCH orders USING INDEX orders_created_at (created_at>? AND created_at<?)

The same applies to strftime('%Y-%m', created_at) = '2026-12'. Use created_at >= '2026-12-01' AND created_at < '2027-01-01' instead.

If you query by the function result often, an expression index works too:

SQL
CREATE INDEX orders_created_day ON orders(date(created_at));
`--SEARCH orders USING INDEX orders_created_day (<expr>=?)

That only works for deterministic calls. Anything involving 'now' is rejected in indexes and generated columns:

Error: stepping, non-deterministic use of datetime() in an index
Error: stepping, non-deterministic use of unixepoch() in a generated column

Common problems

Timestamps are an hour (or several) off. CURRENT_TIMESTAMP and datetime('now') are UTC. Convert with 'localtime' or, better, in the application.

datetime(col) returns NULL. The value is in a format SQLite cannot parse, or it is a Unix timestamp and you left out 'unixepoch'.

Range query misses rows. Mixed T and space separators, a trailing Z on some rows, or a mix of text and integers. Check with typeof() and length().

Query ignores the index. A function is wrapped around the column. Compare the raw column against a range.

near "(": syntax error in CREATE TABLE. A function default needs parentheses: DEFAULT (unixepoch()).

Quick reference

TaskSyntax
Current UTC timestampCURRENT_TIMESTAMP or datetime('now')
Current Unix secondsunixepoch()
Local timedatetime(col, 'localtime')
Unix to textdatetime(col, 'unixepoch')
Text to Unixunixepoch(col)
Custom formatstrftime('%Y-%m-%d %H:%M', col)
Add timedatetime(col, '+7 days')
Start of monthdate(col, 'start of month')
Millisecondsstrftime('%Y-%m-%dT%H:%M:%fZ', 'now')
Default timestampDEFAULT CURRENT_TIMESTAMP
Default Unix timeDEFAULT (unixepoch())
Index-friendly day filtercol >= '2026-12-04' AND col < '2026-12-05'

If you are coming from PostgreSQL, where timestamps are real types with time zone handling, the PostgreSQL timestamp guide covers timestamp versus timestamptz. For grouping by day with gaps filled in, see the recursive date series in the SQLite CTE guide.