Python and SQL Server: datetime data problem

I have a SQL Server table that contains some data datetime

. I am using a Python script with pymssql

to connect to a database and make queries.

The problem I am facing is that when my queries return time and time data, the dates shift and are no longer accurate. For example, one data record in my table refers to the date '2012-03-27', but when I retrieve it and save it in my script as an object datetime

in Python, the date is stored as '2012 -01-03'.

Any ideas on how to fix this? Should I use a library for example pytz

?

Thank!

+3


source to share


2 answers


I'm still not sure what is causing this problem, but I found a solution: Convert the data datetime

to type varchar

when making a query:

select convert(varchar(20),event_time,120) from event_detail;

      

I used to run this query:



select event_time from event_detail;

      

where event_time

is of typedatetime

0


source


I have the same problem with pymssql version 1.02. While not the cleanest aproach I am using the OP's workaround and converting the string value to a python datetime object with the correct values ​​using the dateutil.parser module. Here is the code I'm using, assuming iso_datetime_string contains the ISO datetime string returned by the workaround:



import dateutil.parser as ps

correct_datetime_obj = ps.parse(iso_datetime_string)

      

+1


source







All Articles