11

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.

1
  • 2
    Use parameters. Commented Jun 27, 2014 at 18:12

3 Answers 3

20

Remove the datetime to string conversion and instead use parameters:

....
cursor.execute("insert into currentvalue (value1,currentdatetime) values(?,?)",
               (value1, datetime.datetime.now()))
....
Sign up to request clarification or add additional context in comments.

1 Comment

I experimented. Using parameters, inserting datetimes, or strings in "roughly ISO" format ("2024-09-12 11:39:57"), in ISO format with 'T' in the middle ("2024-09-12T11:39:57") or even with a final timezone marker ("2024-09-12T11:39:57Z") works fine, and string values also work with milliseconds (e.g., "2024-09-12 11:39:57.123"), but datetime.now().isoformat() returns a string with MICROSECONDS ("2024-09-12T11:39:57.123456"), which fails: "Conversion failed when converting date and/or time from character string. (241)". If you have a string already, chop microseconds off or convert to datetime.
7

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+")")

1 Comment

I think your solution not work and it is just like the questioner first attempt. You need at least a string escape.
-1

You can add single quotes:

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

2 Comments

Building SQL queries by sticking strings together is a bad habit
@Chris Thank you for the feedback. I didn't know that I was writing vulnerable SQL injection code. Moving forward, I will keep that in mind. See: realpython.com/prevent-python-sql-injection for how to write safer code for SQL injection attacks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.