Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a datetime type value into SQL database

Tags:

python

sql

pyodbc

Currently using pyodbc python module to get some data into a SQL database.

One of the data fields is datetime, and currently the corresponding python variable (which I am trying to load into the SQL database) is formatted like this:

MM/DD/YY HH:MM:SS ##:##

(where the ##:## is an offset to the OS's timezone). Anyways, I am getting the following error:

"The conversion of a nvarchar data type to a datetime date type resulted in an out-of-range value"

I am wondering what my best option is to rectify this. Should I manually edit the python string so that it is in a different format (like YYYY-MM-DD for instance), or is there a SQL conversion function I can use within the INSERT INTO statement? Ultimately, I guess I'm wondering what specifically SQL looks for to convert to datetime so I can adjust my data accordingly.

Thanks!

like image 363
ykobe323 Avatar asked Feb 05 '26 04:02

ykobe323


1 Answers

Yes there are SQL conversion functions like select convert(varchar, getdate(), 23) for YYY-MM-DD

select convert(varchar, getdate(), 22) 

for MM/DD/YY HH:MM:SS

yes you can use it for INSERT INTO statement like

DECLARE @Tdatetime VARCHAR(MAX) 
SET @Tdatetime = CONVERT( VARCHAR, GETDATE() , 106)
INSERT INTO table_name (column1, column2, ...)
VALUES (@Tdatetime , value2, ...)
like image 121
Nitish Reddy Avatar answered Feb 06 '26 18:02

Nitish Reddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!