我想在Ms-SQL DB中插入一个日期。我该怎么做呢?
这就是我要做的:
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)发布于 2014-08-14 18:08:14
正如我所看到的here,我认为对于数据库中的DateTime值,您必须有一个datetime.datetime对象,而不是一个字符串。所以,只要替换掉
a = (datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")通过
a = datetime.datetime.now()发布于 2018-02-23 08:58:53
对于希望在MS Access数据库中执行此操作的任何人,您可以将数据库表中的字段定义为日期/时间类型,然后在插入或更新查询中将日期-时间值作为单引号分隔的字符串。
此字符串需要采用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 + ':' + secondhttps://stackoverflow.com/questions/25304683
复制相似问题