2

pyodbc handles well datetime.datetime objects with DATETIME column. No special formatting needed.
But it fails with datetime.date objects and DATE column:[HY004] [FreeTDS][SQL Server]Invalid data type (0) (SQLBindParameter)

One way is to insert datetime.date object as string, with .isoformat() method.

But:

d1 = dt.date.today() d2 = dt.datetime.now() print(isinstance(d1, dt.date)) print(isinstance(d1, dt.datetime)) print(isinstance(d2, dt.date)) print(isinstance(d2, dt.datetime)) 

returns

True False True True 

isn't there a better way than testing like that?

if isinstance(d1, dt.date) and not isinstance(d1, dt.datetime): d1 = d1.isoformat() 
3
  • Are you using FreeTDS to connect? What's your FreeTDS and unixODBC configuration? Or are you connecting from Windows? This may be caused by using too low a TDS Version. Commented Jan 23, 2018 at 11:56
  • 1
    "But [pyodbc] fails with datetime.date objects and DATE column" - This is a FreeTDS ODBC issue, not a pyodbc issue per se. pyodbc works fine with DATE columns and datetime.date parameter values when using Microsoft's "ODBC Driver 13 for SQL Server". Commented Jan 23, 2018 at 12:49
  • yup FreeTDS indeed, I modify tags Commented Jan 23, 2018 at 14:38

1 Answer 1

3

I was able to reproduce your issue under FreeTDS 0.91, which is the version distributed by apt install tdsodbc under Ubuntu. However, I was able to successfully use a datetime.date parameter value to populate a DATE column using

  • the latest stable version of FreeTDS (currently 01.00.0080), or
  • Microsoft's "ODBC Driver 13 for SQL Server"
Sign up to request clarification or add additional context in comments.

4 Comments

I was indeed using 0.91 under Debian (ie should be same as your Ubuntu).ii freetds-common 0.91-6 all configuration files for FreeTDS SQL client libraries ii tdsodbc:amd64 0.91-6+b1 amd64 ODBC driver for connecting to MS SQL and Sybase SQL servers
Problem is even with Debian testing (aka Buster) only 0.91-6.1 is avail.
It should work if you set TDS Version to be 7.2 if your configuration with 0.91. If you have it set to 8.0 or 7.1 or less, it doesn’t support the DATE type.
@FlipperPA - I tried adding ;TDS_version=7.2 to my connection string under 0.91 but it didn't solve this particular problem (parameter binding). I also tried ;TDS_version=7.3 but apparently 0.91 does not support protocol version 7.3 because TDSDUMP told me that it was actually using protocol version 4.2 (the default).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.