There is a general recipe for storing any serializable Python object in an sqlite table.
- Use
sqlite3.register_adapter to register a function to convert a Python object to int, long, float, str (UTF-8 encoded), unicode, or buffer. - Use
sqlite3.register_converter to register a function to convert text to a Python object. The input is always text because internally, sqlite saves everything as text.
Here's what the code for datetime.time objects looks like:
import sqlite3 import datetime as DT def adapt_timeobj(timeobj): return ((3600*timeobj.hour + 60*timeobj.minute + timeobj.second)*10**6 + timeobj.microsecond) def convert_timeobj(val): val = int(val) hour, val = divmod(val, 3600*10**6) minute, val = divmod(val, 60*10**6) second, val = divmod(val, 10**6) microsecond = int(val) return DT.time(hour, minute, second, microsecond)
You can use inequalities in SQL, but note that the compared values โโare those returned by adapt_timeobj objects, not datetime.time . Fortunately, if the adapt_timeobj function returns integers that are ordered in the same order as the corresponding datetime.time objects (as they do above), then the inequalities in SQL will work as desired.
cur.execute("select timecol from test where timecol < ?", [DT.time(4,5,6)]) print(cur.fetchall()) # [(datetime.time(1, 2, 3, 4),)] cur.execute("select timecol from test where timecol < ?", [DT.time(8,0,0)]) print(cur.fetchall()) # [(datetime.time(1, 2, 3, 4),), (datetime.time(5, 6, 7, 8),)] con.commit() cur.close() con.close()
Note. If you look in the change history, you will see a simpler alternative for adapt_timeobj and convert_timeobj , which stores data as str , and not as int . It is simpler, but saving data as an int is faster and more efficient.