Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert into a mysql database timestamp

I have a part in my python script that I need to insert some data into a table on a mysql database example below:

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.

THanks

like image 289
Steven Wilson Avatar asked Dec 02 '15 15:12

Steven Wilson


3 Answers

Simply use the database NOW() function, e.g.

timestamp="NOW()"
insert_data = "INSERT into test (test_date,test1,test2) values (%s,%s,%s)"
cur.execute(insert_data,(test_date,test1,test2,timestamp))
db.commit()
db.close()
like image 69
yonilobo Avatar answered Sep 22 '22 02:09

yonilobo


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()
like image 28
Aman Gupta Avatar answered Oct 06 '22 13:10

Aman Gupta


Timestamp creating can be done in one line, no need to use time.time(), just:

from datetime import datetime

timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
like image 14
Artem Avatar answered Oct 06 '22 14:10

Artem