0

I'm attempting to use python to insert a timestamp into column created_by of a mysql db.

Here is my database table setup..

CREATE TABLE temps (
temp1 FLOAT, temp2 FLOAT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

temp1 and temp2 and populating correctly but receiving an error for the timestamp

 Warning: Data truncated for column 'created_at' at row 1
  cursor.execute("""INSERT INTO temps VALUES (%s,%s,%s)""",(avgtemperatures[0],avgtemperatures[1],st[2]))
((71.7116, 73.2494, None),)

Here is the section of python script that inserts information into the db.

 #connect to db
db = MySQLdb.connect("localhost","user","password","temps" )

 #setup cursor
cursor = db.cursor()
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

sql = """CREATE TABLE IF NOT EXISTS temps (
  temp1 FLOAT,  
  temp2 FLOAT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"""
cursor.execute(sql)


 #insert to table
try:
    cursor.execute("""INSERT INTO temps VALUES (%s,%s,%s)""",(avgtemperatures[0],avgtemperatures[1],st[2]))
    db.commit()
except:     
    db.rollback()


 #show table
cursor.execute("""SELECT * FROM temps;""")

print cursor.fetchall()
((188L, 90L),)

db.close()

Here is a dump of the db:

Dumping data for table temps
temp1   temp2   created_at
71.7116 73.2494 0000-00-00 00:00:00

1 Answer 1

2

You should have to set the datetime. Your created_at column will automatically be updated to the current time stamp at insertion. See documentation at Automatic Initialization and Updating for TIMESTAMP.

You statement should be

cursor.execute("""INSERT INTO temps VALUES (%s,%s,CURRENT_TIMESTAMP)""",(avgtemperatures[0],avgtemperatures[1]))
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.