I'm working with sqlite and I'm struggling a little bit handling date and time. I have a table created with a field Date
of type text
.
I need to set that field to a custom time, f. ex: '2021-01-18 05:07:37'
that I get with this code (I'm using now datetime just as an example)
date = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
print(date)
# 2021-01-18 05:07:37
Then I create a record with this date:
command = f'''INSERT INTO Twitter (Date, Content)
VALUES(datetime({date}), "Some cool content")'''
print(command)
# INSERT INTO Twitter (Date, Content)
VALUES(datetime(2021-01-18 05:13:54), "Some cool content")
conn.execute(command)
conn.commit()
This code raises an error:
OperationalError
Traceback (most recent call last)in
2 VALUES(datetime({date}), "Some cool content")'''
3 print(command)
----> 4 conn.execute(command)
5 conn.commit()OperationalError: near "05": syntax error
I'm not sure what is wrong, I think I'm using sqlite datetime format correctly, but the error seems to be related to the format somehow, any suggestions about how can I solve this?
EDIT
I noted that if I add manually the date to the sqlite command, it works nice, like doing this:
command = f'''INSERT INTO Twitter (Date, Content)
VALUES(datetime('2021-01-18 05:07:37'), "Some cool content")'''
The issue appears when I dynamically add the datetime as a variable, I'm not sure if I'm missing anything.
The issue is that the sqlite is not familiar with the datetime
type of python so by trying to insert datetime(2021-01-18 05:13:54)
into Date
field you're receiving OperationalError: near "05": syntax error
and when you're adding the single quotes like '2021-01-18 05:07:37'
the date is converted to a string and able to be inserted into the table.
You can try to do
command = f'''INSERT INTO Twitter (Date, Content)
VALUES(datetime('{date}'), "Some cool content")'''
OR
command = f'''INSERT INTO Twitter (Date, Content)
VALUES(datetime("{date}"), "Some cool content")'''
Note: the sqlite datetime
function expecting a string as described here https://sqlite.org/lang_datefunc.html
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.