Python Forum
Date format convert problem for SQL server
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Date format convert problem for SQL server
#1
Exclamation 
Hello everyone,

In an application I wrote, I need to change the date information entered by the user in the format DD/MM/YYYY to YYYY/MM/DD in order to write it to the SQL database field.

I am using the following code structure for this change, and I get the correct output as YYYY/MM/DD.

However, when it comes to writing this data to SQL, I receive the following error message.

I am using 'date' or 'datetime' as the data type in the database, but it doesn't make a difference.

Does anyone have any ideas on this issue?

ERROR MESSAGES:

Error: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Error converting data type nvarchar to numeric. (8114) (SQLExecDirectW)')


CODE:

from datetime import datetime, date

date = request.form['DATE']
print(date)
date_str = datetime.strptime(date, '%d/%m/%Y')
date_sql_format = datetime.strptime(date_str.strftime('%Y-%m-%d'), '%Y-%m-%d').date()
print(date_sql_format)
conn = pyodbc.connect(connection_string)
cursor = conn.cursor()
cursor.execute('''INSERT INTO dbo.Users (DATE) VALUES (?) ''', (date_sql_format))
conn.commit()
cursor.close()
conn.close()

date                 = 05/08/2024
date_sql_format = 2024-08-05
Reply
#2
If changing an existing row in a table, you need to use 'UPDATE', not 'INSERT'
Reply
#3
(Aug-08-2024, 11:32 AM)Larz60+ Wrote: If changing an existing row in a table, you need to use 'UPDATE', not 'INSERT'

We are not updating an existing record, we are trying to enter a new date. Therefore, we are using INSERT.
Reply
#4
Please post output and the entire error message, including any traceback.

According to the documentation, parameters is a sequence. I think you meant (date_sql_format) to be a tuple, but it is just parenthesis around a value. When making a tuple that contains a single value, use a trailing comma, (date_sql_format,).

Because you are not passing a tuple, the execute command uses date_sql_format as the parameters. Instead of adding "2024-08-05" I think it is trying to add ("2", "0", "2", "4", "-", "0".....) you get the idea.

Try this:
cursor.execute('''INSERT INTO dbo.Users (DATE) VALUES (?) ''', (date_sql_format,))
Reply
#5
(Aug-08-2024, 05:46 PM)deanhystad Wrote: Please post output and the entire error message, including any traceback.

According to the documentation, parameters is a sequence. I think you meant (date_sql_format) to be a tuple, but it is just parenthesis around a value. When making a tuple that contains a single value, use a trailing comma, (date_sql_format,).

Because you are not passing a tuple, the execute command uses date_sql_format as the parameters. Instead of adding "2024-08-05" I think it is trying to add ("2", "0", "2", "4", "-", "0".....) you get the idea.

Try this:
cursor.execute('''INSERT INTO dbo.Users (DATE) VALUES (?) ''', (date_sql_format,))

Thank you for the reply.

Since there are many parameters within the application, I wanted to include the problematic area.

Below is the code related to the database connection and the user input sections, as well as the error message.

Among these parameters, the lines below specifically convert the date information into a format suitable for the SQL server.

All data, except for the date information, is being successfully recorded.


Quote:
gorusme_tarihi = request.form['Gorusme_Tarihi']
print(gorusme_tarihi)
gorusme_tarihi_str = datetime.strptime(gorusme_tarihi, '%d/%m/%Y')
gorusme_tarihi_sql_format = datetime.strptime(gorusme_tarihi_str.strftime('%Y-%m-%d'), '%Y-%m-%d').date()
print(gorusme_tarihi_sql_format)



app = Flask(__name__)
app.secret_key = 'secretkey' 
Bootstrap(app)

# Database bconnection
server = '192.168.1.1'
database = 'TESTDB01'
username = 'api'
password = 'Password'
driver = '{ODBC Driver 17 for SQL Server}'
connection_string = f'DRIVER={driver};SERVER={server};PORT=1433;DATABASE={database};UID={username};PWD={password}'


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/kayit', methods=['POST'])
def kayit():
    try:
        donem = request.form['Donem']
        akis_no = request.form['Akis_No']
        gsm = request.form['GSM']
        name = request.form['Name']
        mail = request.form['Mail']
        birim = request.form['Birim']
        bolum = request.form['Bolum']
        departman = request.form['Departman']
        pozisyon = request.form['Pozisyon']
        unvan = request.form['Unvan']
        jci = request.form['JCI']
        bu_head = request.form['BU_Head']
        yonetici = request.form['Yonetici']
        hrbp = request.form['HRBP']
        calisma_lokasyonu = request.form['Calisma_Lokasyonu']
        proje = request.form['Proje']
        cv_kaynagi = request.form['CV_Kaynagi']
        aday_durumu = request.form['Aday_Durumu']
        gorusme_tarihi = request.form['Gorusme_Tarihi']
        print(gorusme_tarihi)
        gorusme_tarihi_str = datetime.strptime(gorusme_tarihi, '%d/%m/%Y')
        gorusme_tarihi_sql_format = datetime.strptime(gorusme_tarihi_str.strftime('%Y-%m-%d'), '%Y-%m-%d').date()
        print(gorusme_tarihi_sql_format)
        conn = pyodbc.connect(connection_string)
        cursor = conn.cursor()
        cursor.execute('''                       
            INSERT INTO dbo.Users (Donem, Akis_No, GSM, Name, Mail, Birim, Bolum, Departman, Pozisyon, Unvan, JCI, Bu_Head, Yonetici, HRBP, Calisma_Lokasyonu, Proje, CV_Kaynagi, Aday_Durumu, Gorusme_Tarihi)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ''', (donem, akis_no, gsm, name, mail, birim, bolum, departman, pozisyon, unvan, jci, bu_head, yonetici, hrbp, calisma_lokasyonu, proje, cv_kaynagi, aday_durumu, gorusme_tarihi_sql_format))
        conn.commit()
        cursor.close()
        conn.close()

        flash('Kaydiniz Gerçekleşti', 'success')

    except Exception as e:
        flash('Kaydiniz gerçekleşmedi, tekrar deneyin', 'danger')
        print(f"Error: {e}")
    return redirect(url_for('index'))
Quote:10.251.3.11 - - [09/Aug/2024 08:56:15] "GET / HTTP/1.1" 200 -
10.251.3.11 - - [09/Aug/2024 08:56:17] "GET /favicon.ico HTTP/1.1" 404 -
05/08/2024
2024-08-05
Error: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Error converting data type nvarchar to numeric. (8114) (SQLExecDirectW)')
10.251.3.11 - - [09/Aug/2024 08:56:23] "POST /kayit HTTP/1.1" 302 -
10.251.3.11 - - [09/Aug/2024 08:56:23] "GET / HTTP/1.1" 200 -
Reply
#6
No need to change the date around, MySQL can accept any format, as long as you advise it about the format:

Just use STR_TO_DATE('05/08/2024', '%d/%m/%Y')

Quote:INSERT INTO babydb.sales_agro_products (customer_id, product_name, product_class, product_price_kG, amount_ordered, sales_value, Date) VALUES ('Big John', 'Kill Everything', 'product_class', 112.34, 678, 76166.52, STR_TO_DATE('05/08/2024', '%d/%m/%Y'))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Invalid Date Format fo Cached Files jland47 1 487 May-22-2024, 07:04 PM
Last Post: deanhystad
  convert to bin problem kucingkembar 3 612 Apr-19-2024, 12:53 PM
Last Post: kucingkembar
  Compare current date on calendar with date format file name Fioravanti 1 816 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Python date format changes to date & time 1418 4 1,226 Jan-20-2024, 04:45 AM
Last Post: 1418
Thumbs Up Convert word into pdf and copy table to outlook body in a prescribed format email2kmahe 1 1,125 Sep-22-2023, 02:33 PM
Last Post: carecavoador
  Convert From PDf into JPEG Problem koklimabc 4 1,574 Sep-05-2023, 06:44 AM
Last Post: Gribouillis
  Review my code: convert a HTTP date header to a datetime object stevendaprano 1 2,693 Dec-17-2022, 12:24 AM
Last Post: snippsat
  Modifying a date format jehoshua 17 4,144 Oct-29-2022, 08:44 PM
Last Post: jehoshua
  Convert Json to table format python_student 2 8,070 Sep-28-2022, 12:48 PM
Last Post: python_student
  Convert .xlsx to Format as Table bnadir55 0 1,102 Aug-11-2022, 06:39 AM
Last Post: bnadir55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020