This lesson demonstrates how to work with SQLite date and timestamp types in Python and vice-versa. Most of the time, we need to insert Python date or DateTime value into an SQLite table. Also, we need to read the SQLite date and timestamp values stored in the SQLite3 database and convert them into Python date and DateTime types.
Also Read:
Table of contents
Prerequisites
Before executing the following program, please make sure you have an SQLite table with a timestamp as a column from which you want to retrieve/insert data.
For this lesson, I am using the ‘new_developers’ table present in my SQLite database.
If a table is not present in your SQLite database, then please refer to the following articles: –
Python example to insert/Retrieve DateTime from SQLite table
In a usual scenario, when you execute the insert query with the DateTime object, the Python sqlite3 module converts it into a string format instead of an actual DateTime. And when you run a SELECT query from Python to read DateTime values from SQLite table, the sqlite3 module will convert it into a string object. Let’s understand this scenario with a simple example.
Output:
Connected to SQLite Developer added successfully Mark joined on 2019-06-28 21:12:35.799206 joining date type is <class 'str'> sqlite connection is closed
As we can see, we inserted a date object, but when we retrieved the details from a table, we got a string type. But we don’t want string type. We want the DateTime type so we can directly use it.
To solve this problem, use detect_types as PARSE_DECLTYPES and PARSE_COLNAMES as arguments in the connect method of the sqlite3 module.
sqlite3.PARSE_DECLTYPES
If you use this parameter in the connect method, then the sqlite3 module parses the declared type for each column it returns.
It will parse the declared type then use the type converters dictionary to execute the converter function registered for that type there.
sqlite3.PARSE_COLNAMES
If you use this parameter in the connect method, then the SQLite interface parses the column name for each column it returns. It will use the converters dictionary and then use the converter function found there to return the value.
Let see the example now. In this example, when we read DateTime from the SQLite table we must get the joining date type as a datetime.
Output:
Connected to SQLite Developer added successfully Mark joined on 2019-06-28 20:57:32.352790 joining date type is <class 'datetime.datetime'> sqlite connection is closed
As you can see when we retrieved the joining date from SQLite table and we got the result in datetime.datetime type.
Next Steps:
To practice what you learned in this article, Solve a Python SQLite Exercise project to practice database operations.
