2

I want to save dates and times into a mysql table and work with them later on. How to convert a tuple to a datetime to work with this value?

from datetime import datetime, timedelta
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="**USER**",
  passwd="**PASSWORT**",
  database="**DATABASE"**
)

# Table already created like this:
# mycursor.execute("CREATE TABLE events2 (id INT AUTO_INCREMENT PRIMARYKEY, name VARCHAR(255), startdate DATETIME, enddate DATETIME, deadline INT, position INT, reminder INT)")

name = "Testevent"
startdate = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
enddate = datetime.now() + timedelta(days=14)
deadline = 24
position = 25
reminder = 1

sql = "INSERT INTO events2 (name, startdate, enddate, deadline, position, reminder) VALUES (%s, %s, %s, %s, %s, %s)"
val = (name, startdate, enddate, deadline, position, reminder)
mycursor.execute(sql, val)
mydb.commit()

mycursor = mydb.cursor()

mycursor.execute("SELECT startdate FROM events2 WHERE id = '7'")

myresult = mycursor.fetchone()

print(myresult)
y = myresult + timedelta(days=14)

Output:

(datetime.datetime(2018, 8, 20, 18, 31, 42),)
Traceback (most recent call last):
  File ".../Create_event.py", line 54, in <module>
    y = myresult + timedelta(days=14)
TypeError: can only concatenate tuple (not "datetime.timedelta") to tuple

1 Answer 1

1

myresult is a tuple containing one single object : a datetime.datetime. Then you have to do :

y = myresult[0] + timedelta(days=14)

This is easily noticeable thanks to your print, we see that the datetime object is contained inside a tuple (which syntax is (elem1, [elem2, ...]))

Sign up to request clarification or add additional context in comments.

1 Comment

or it could be done at the function myresult = mycursor.fetchone()[0]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.