Python 插入mysql数据库时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34046634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
insert into a mysql database timestamp
提问by Steven Wilson
I have a part in my python script that I need to insert some data into a table on a mysql database example below:
我在我的 python 脚本中有一个部分,我需要在下面的 mysql 数据库示例中的表中插入一些数据:
insert_data = "INSERT into test (test_date,test1,test2) values (%s,%s,%s)"
cur.execute(insert_data,(test_date,test1,test2))
db.commit()
db.close()
I have a couple of questions what is incorrect with this syntax and how is possible to change the VALUES to timestamp instead of %s for string? Note the column names in the database are the same as the data stored in the variables in my script.
我有几个问题,这种语法有什么不正确,以及如何将 VALUES 更改为时间戳而不是字符串的 %s?请注意,数据库中的列名与脚本中变量中存储的数据相同。
THanks
谢谢
采纳答案by Aman Gupta
try this:
尝试这个:
import MySQLdb
import time
import datetime
ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="db1")
x = conn.cursor()
try:
x.execute("""INSERT into test (test_date,test1,test2) values(%s,%s,%s)""",(timestamp,test1,test2))
conn.commit()
except:
conn.rollback()
conn.close()
回答by Artem
Timestamp creating can be done in one line, no need to use time.time(), just:
时间戳创建可以在一行中完成,不需要使用 time.time(),只需:
from datetime import datetime
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')