python - 在Ms-Sql中插入DateTime字段

1 投票
2 回答
13590 浏览
提问于 2025-04-18 17:16

我想把一个日期插入到Ms-SQL数据库里。我该怎么做呢?

这是我现在的做法:

a = (datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
data =  {'AWB_Number':'1','Weight':'1','Length':'1','Height':'1','Width':'1','Customer_Name':'Naaptol','Scan_Time': a,'Series_Flag':'Others'}

data = (
        data['AWB_Number'], data['Weight'], data['Length'], data['Height'],
        data['Width'], data['Customer_Name'], data['Scan_Time'] ,data['Series_Flag']
        )

print data


con_string = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (aramex_dsn, aramex_user, aramex_password, aramex_database)
cnxn = pyodbc.connect(con_string)

cursor = cnxn.cursor()

cursor.execute("insert into data_AutoScale_DELHUB VALUES (%s, %s, %s, %s, %s, %s, %s, %s)" % data)
cnxn.commit()

cnxn.close()

但是它返回了一个错误,内容是:

Traceback (most recent call last):
  File "tests.py", line 39, in <module>
    cursor.execute("insert into data_AutoScale_DELHUB VALUES (%s, %s, %s, %s, %s, %s, %s, %s)" % data)
pyodbc.ProgrammingError: ('42000', "[42000] [FreeTDS][SQL Server]Incorrect syntax near '09'. (102) (SQLExecDirectW)")

那这是怎么回事呢?

下面是数据库的结构:

    AWB_Number = models.CharField(max_length = 255)
    Weight = models.CharField(max_length = 255)
    Length = models.CharField(max_length = 255)
    Width = models.CharField(max_length = 255)
    Height = models.CharField(max_length = 255)
    Customer_Name = models.CharField(max_length = 255)
    Scan_Time = models.DateTimeField(db_index = True)
    Series_Flag = models.CharField(max_length = 255)

2 个回答

0

如果你在这里是想在MS Access数据库中实现这个功能,可以把数据库表里的字段定义为日期/时间类型。然后在你的插入(INSERT)或更新(UPDATE)查询中,把日期时间值放在单引号里。

这个字符串需要用Access能识别的日期/时间格式,比如:'2/19/2018 11:44:22 PM' 或者 '02/19/2018 23:44:22'。ODBC驱动程序会处理其他的事情,最终日期时间会作为有效的数据库日期/时间存入你的表中。

我没有在MS-SQL上试过这个,但根据经验,它的工作方式应该差不多。下面是一些代码,用来创建适合MS Access的格式字符串:

import pandas as pd
def MSDate_Format_from_Article(self, datestr: str) -> str:
    # Start with the format: 2018-02-14T21:57:55Z
    try:
        datetime_obj = pd.to_datetime(datestr)
    except:
        log("ERROR: Bad Date!")
        return "01/01/1980 00:00:00"
    else:
        year = "{:04d}".format(datetime_obj.year)
        month = "{:02d}".format(datetime_obj.month)
        day = "{:02d}".format(datetime_obj.day)
        hour ="{:02d}".format(datetime_obj.hour)
        minute = "{:02d}".format(datetime_obj.minute)
        second = "{:02d}".format(datetime_obj.second)
        # Return the date as a string in the format: 02/19/2018 23:44:22
        return month + '/' + day + '/' + year + ' ' + hour + ':' + minute + ':' + second
7

我在这里看到,数据库中的日期时间值必须使用datetime.datetime对象,而不是字符串。所以,只需要把

a = (datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")

替换成

a = datetime.datetime.now()

撰写回答