SQLite does not have datatypes to store date or time. Instead it provides builtin functions that are capable of storing dates and times as TEXT, REAL or INTEGER values.
- TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS")
- REAL as Julian day numbers
- INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC
Date and Time Functions
SQLite supports five date and time functions as follows:
-
date(time-value, modifier, modifier, ...)
-
time(time-value, modifier, modifier, ...)
-
datetime(time-value, modifier, modifier, ...)
-
julianday(time-value, modifier, modifier, ...)
-
strftime(format, time-value, modifier, modifier, ...)
Refer to following for more details: https://sqlite.org/lang_datefunc.html
Python code to Store, Retrieve and Manipulate DateTime in SQLite
SQLite3 comes bundled with Python 3 so we can directly start using it.
import sqlite3
conn = sqlite3.connect('my.db')
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS expense (name TEXT, date TEXT, time TEXT)")
cur.execute("INSERT INTO expense VALUES ('Grocery', date('now'), time('now'))")
cur.execute("SELECT * FROM expense WHERE date > '2021-02-19')
conn.commit()
conn.close()