0

I would like to insert datetime into sqlite using Python.

I tried using Python's datetime and strftime but it didn't work.

Test's time field has the type of Numeric (Datetime).

from datetime import datetime as dt

rows = db.execute(
    'INSERT INTO test (time) VALUES (:time)',
    time=dt.now().strftime('%Y-%m-%d %H:%M:%S'))

RuntimeError: (sqlite3.OperationalError) near "'2019-05-19 17:14:25'": syntax error [SQL: INSERT INTO test (time) VALUES ('2019-05-19 17:14:25')]

1
  • copy query and run directly in database and maybe it gives you more information about problem. Numeric may means number like timestamp Commented Jul 13, 2019 at 8:32

1 Answer 1

1

You could use :-

rows = db.execute("INSERT INTO test (time) VALUES (datetime('now'))")

The column type is basically irrelevant as in SQLite you can store any type of value in any type of column.

With the exception of the special rowid column or an alias of the rowid column (if the column is defined using INTEGER PRIMARY KEY then it is an alias of the rowid column (or with the AUTOINCREMENT keyword)). An alias of the rowid column must be an integer up to 64 bit signed.

Working Example

import sqlite3
drop_sql = "DROP TABLE IF EXISTS test"
crt_sql = "CREATE TABLE IF NOT EXISTS test (time NUMERIC, time2 TEXT, time3 BLOB, time4 REAL, time5 INTEGER )"
db = sqlite3.connect("test.db")
rows = db.execute(drop_sql)
rows = db.execute(crt_sql)
rows = db.execute("INSERT INTO test VALUES(datetime('now'),datetime('now'),datetime('now'),datetime('now'),datetime('now'))")
cursor = db.cursor()
cursor.execute("SELECT * FROM test")
for row in cursor:
    print("Time is " + row[0], "\nTime2 is " + row[1],"\nTime3 is " + row[2], "\nTime4 is " + row[3],"\nTime5 is " + row[4])
db.commit()
db.close()

Result :-

Time is 2019-07-13 08:59:28 
Time2 is 2019-07-13 08:59:28 
Time3 is 2019-07-13 08:59:28 
Time4 is 2019-07-13 08:59:28 
Time5 is 2019-07-13 08:59:28
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.