Robin Le Sage
Robin Le Sage

Reputation: 109

inserting timestamp in mysql table in python

bid, best_bid_quantity are floats, target_date is set as timestamp in my db.

get timestamp

target_date_time_ms = (k.lastRestRequestTimestamp) 

base_datetime = datetime.datetime( 1970, 1, 1 )

delta = datetime.timedelta( 0, 0, 0, target_date_time_ms )

target_date = base_datetime + delta

timestamp = target_date

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                         user="root",         # your username
                         passwd="lolilol",  # your password
                         db="test")        # name of the data base

cur = db.cursor()

try:

   cur.execute("""INSERT INTO test1 (heure, prix, quantite) VALUES ({},{},{})""".format(target_date, bid, best_bid_quantity))
   db.commit()

except:
    print('did not insert')
    db.rollback()

db.close()

error --> it goes to except when I add the target_date

Upvotes: 0

Views: 3297

Answers (1)

user2556381
user2556381

Reputation:

Try using time.strftime():

time.strftime('%Y-%m-%d %H:%M:%S', target_date.timetuple())

The .timetuple() method is required to convert the datetime.datetime object of target_date into a time_struct struct, which can then be used in the call to time.strftime.

Upvotes: 1

Related Questions