How do I insert datetime value into a SQLite database?
Insert a datetime in SQLite using the YYYY-MM-DD HH:MM:SS format. To add the current time:
For a specific datetime, keep the format consistent:
Stick to the golden format
In SQLite, the golden format for storing datetime values is YYYY-MM-DD HH:MM:SS. Get it right, and SQLite will behave like the best SQL database around!
Parameterized queries to the rescue!
Using parameterized queries helps prevent injection attacks and ensures the values are inserted correctly. Here's a summarized example in Python's sqlite3
:
TEXT datatype: Your trusty steed
Opt for the TEXT datatype to store datetime values in SQLite. This will ensure compatibility across different databases and systems.
Decoding fractional seconds
SQLite also understands fractional seconds. Just add them during insertion, as follows:
Unleashing SQLite's datetime functions
SQLite comes with some power-packed datetime functions like STRFTIME
, DATE
, TIME
, etc.
Compatibility alert: Avoid MySQL habits
Remember, SQLite might be polite, but it doesn't understand MySQL’s NOW()
. Stick to DATETIME('now')
or CURRENT_TIMESTAMP
.
Tackling retrieval issues
Encountered errors when retrieving data? Put on your detective cap and compare the stored format with the format used in the SELECT query.
A quick run-down: SQLite datetime functions
DATETIME
: Manage datetime values.STRFTIME
: Custom-format your dates and times.DATE
: Extract the date from a datetime.TIME
: Extract only the time from a datetime.
Was this article helpful?