How to store and retrieve date into Sqlite3 database using Python?


You can very easily store and retrieve date into Sqlite3 database using the sqlite3 module. When inserting the date in the database, pass the date directly and Python handles it automatically.

Example

import sqlite3
import datetime
conn = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
conn.execute('''CREATE TABLE TEST (ID TEXT PRIMARY KEY NOT NULL, DATE DATE)''')
# Save changes
conn.commit()
# Insert the object directly
conn.execute("INSERT INTO TEST (ID,DATE) VALUES (?, ?)", ('My date', datetime.date(2018, 1, 4)))
conn.commit()
print("Record inserted")

Output

This will give the output −

Record inserted

Now when you will fetch the values from the database, you will get the date already parsed to the datetime object.

Example

import sqlite3
import datetime
conn = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cursor = conn.execute("SELECT ID,DATE from TEST")
for row in cursor:
    print row

Output

This will give the output −

(u'foo', datetime.date(2014, 4, 28))

Updated on: 12-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements