【问题标题】:Using pymssql to insert datetime object into SQL Server使用 pymssql 将 datetime 对象插入 SQL Server
【发布时间】:2026-02-04 11:30:01
【问题描述】:

如何使用 pymssql 插入数据时间对象?我知道 SQL Server 表需要一个日期时间对象,比如说在位置 3。我已经尝试了所有这三个:

cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', datetime.datetime.now())")
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', 20130410)")
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', '20130410')")
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', GETDATE())")

我每次都得到同样的错误:

OperationalError: (241, 'Conversion failed when converting date and/or time from character string.DB-Lib error message 241, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n')

我已经翻遍了那里的小文档,并反复搜索。

编辑:次要问题是字段长度问题。请参阅关于已接受答案的第一条评论。

【问题讨论】:

    标签: python sql-server windows pymssql


    【解决方案1】:

    您正在尝试插入一个未格式化为日期的字符串 (datetime.datetime.now(), 20130410, '20130410', GETDATE()),因此 sql server 无法从中解析日期...

    所以试试这个...

    cursor.execute("
        INSERT INTO MyTable
        VALUES(
            1,
            'Having Trouble',
            '" + str(datetime.datetime.now()) + "'
        )
    ")
    

    【讨论】:

    • 就是这样。这是一个字段长度问题。 datetime.datetime.now() 给了我'2013-04-11 10:08:29.512000'。我在 SQL Server Management Studio 中尝试过,但失败了。但是'2013-04-11 10:08:29.512' 有效。所以我在做cursor.execute("INSERT INTO MyTable VALUES(2, 'having trouble', '" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "')"),它正在工作。 (也回复:格式:它可能还需要明确的连字符 - 不确定。)非常感谢您的帮助。
    • @tanaydin 在你说“mysql”的答案中,不应该是“MS SQL”吗?
    • 总是使用 datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') 不是更安全吗 - str 的输出可能会改变不知何故,这不是很明显,这不是巧合吗?
    【解决方案2】:

    您可以使用此代码:

    # a tuple with the data to be stored in db
    data = (1, 'Having Trouble', datetime.datetime.now())
    # perform the query 
    cursor.execute("INSERT INTO MyTable VALUES(%s, %s, %s)" % data)
    

    【讨论】:

    • tanaydin 的解决方案是对的!在这里,我建议您在将数据插入数据库之前使用更灵活的方式使用元组来存储数据。
    • 我明白了。曾经尝试过这种方式。这是我得到的(我的表实际上期待两个日期时间):sqldata = (2, 'url', 'raw', 'uni', 'text', 'mark', 'auth', 'ttitle', 'wtitle', datetime.datetime.now(), datetime.datetime.now(), 'ctype') 然后cursor.execute("INSERT INTO WebContent VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" % sqldata) 产生ProgrammingError: (102, "Incorrect syntax near '18'.DB-Lib error message 102, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
    • 见下文。我一定有一个错误。
    • sqldata 变量中列的顺序是否与WebContent 表中的列的顺序相同?也许您需要在 VALUES 之前指定表的列名。可以在此处找到一些示例:mysql-python.sourceforge.net/MySQLdb.html
    • 使用MySQLdb模块怎么样?
    【解决方案3】:

    试试这个:

    timeStamp = str(datetime.datetime.now())[0:-3]
    

    这种时间戳格式可以被MS SQL SERVER转换,可以在pymssql中插入一个datetime类型的对象

    【讨论】:

    • Strftime 更明确,在我看来,但这又是一个字段长度问题,您的解决方案直接说明了这一点。
    【解决方案4】:

    对于面临同样问题的其他人,我的问题是不同的。

    我的年份被解析为 0014;我认为这被解释为 2014 年。我花了一段时间才意识到发生了什么。

    pymssql 进来的地方是 smalldate 类型没有将 0014 识别为年份,无法进行转换。

    【讨论】: