简体   繁体   中英

How to insert datetime into sqlite3 database using Python?

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')]

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM