Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting datetime into a MS SQL table using pyodbc

I'm trying to insert a datetime value into a MS SQL Server table using pyodbc. If I do it manually, something like:

cursor.execute("""insert into currentvalue(value1,currentdatetime)
                                    values(55,'2014-06-27 16:42:48.533')""")

I have no problem at all, but when I try to do:

currenttime = str(datetime.datetime.now())
cursor.execute("""insert into currentvalue(value1,currentdatetime) 
                                    values(55,"""+ currenttime+")")

I got this error:

SQL server Incorrect syntax near '07' which i think is the number after the date and starting the time.

Also I tried this:

currenttime = "'"+str(datetime.datetime.now())+"'"

and now this error comes up:

Conversion failed when converting date and/or time from character string.

like image 232
user3784140 Avatar asked Jun 27 '14 17:06

user3784140


People also ask

How do I insert datetime in MS SQL?

Always use the format YYYYMMDD to insert the date into database. This is the default format that SQL Server uses. It is also the safe format and can be interpreted only in one way.

How do I create a datetime table in SQL?

SQL Declare variable date To declare a date variable, use the DECLARE keyword, then type the @variable_name and variable type: date, datetime, datetime2, time, smalldatetime, datetimeoffset. In the declarative part, you can set a default value for a variable.

Can you cast date to datetime in SQL?

We can convert the Date into Datetime in two ways. Using CONVERT() function: Convert means to change the form or value of something. The CONVERT() function in the SQL server is used to convert a value of one type to another type. Convert() function is used to convert a value of any type to another datatype.


2 Answers

You can also use datetime.strftime() to convert datetime object to string in the way you need. str(datetime) is bad idea.

currenttime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") cursor.execute("""insert into currentvalue(value1,currentdatetime) values(55,"""+ currenttime+")")

like image 132
user2232196 Avatar answered Sep 21 '22 10:09

user2232196


Remove the datetime to string conversion and instead use parameters:

....
cursor.execute("insert into currentvalue (value1,currentdatetime) values(?,?)",
               (value1, datetime.datetime.now()))
....
like image 23
Bryan Avatar answered Sep 22 '22 10:09

Bryan