【问题标题】:Converting a tuple to a datetime将元组转换为日期时间
【发布时间】:2019-01-26 20:53:39
【问题描述】:

我想将日期和时间保存到 mysql 表中,以便以后使用。如何将元组转换为日期时间以使用此值?

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)

输出:

(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

【问题讨论】:

    标签: python mysql datetime tuples


    【解决方案1】:

    myresult 是一个包含一个对象的元组:datetime.datetime。然后你必须这样做:

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

    感谢您的print,这很容易引起注意,我们看到datetime 对象包含在一个元组中(语法为(elem1, [elem2, ...])

    【讨论】:

    • 或者可以在myresult = mycursor.fetchone()[0]函数中完成
    猜你喜欢
    • 2019-04-21
    • 2012-09-06
    • 2018-04-24
    • 2011-12-06
    • 2016-10-05
    • 2012-11-08
    • 2019-01-15
    • 2018-08-30
    • 2014-07-01
    相关资源
    最近更新 更多