3

I have a SQL Server table that contains some datetime data. I'm using a Python script with pymssql to connect to the database and execute queries.

The problem I'm having is that when my queries return datetime data, the dates are shifted and are no longer accurate. For example, one data entry in my table is for the date '2012-03-27', but when I retrieve it and store it in my script as a datetime object in Python, the date is stored as '2012-01-03'.

Any ideas on how to fix this? Should I be using a library like pytz?

Thanks!

5
  • This seems incredibly strange. There's no way something 'converting' the 27th March to the 3rd January could be a timezone issue. Not as far as I can see. Could you paste the related code section from where you get the date to where you store it? Commented Apr 10, 2012 at 12:57
  • you're obviously looking at the wrong data. provide the code. Commented Apr 10, 2012 at 13:01
  • Unless something out of my head is happening (which often does though!), this should not happen. But things happens. Have you checked your code thoroughly. Commented Apr 10, 2012 at 13:01
  • 2
    Please post your code! I am thinking about your problem for a long time now assuming it as an interesting case and finally hit a dead end! As of curiosity, I want to see you code...desperately. Commented Apr 10, 2012 at 13:14
  • This looks like a month <-> day switch that is passing errors silently. 3/27 somewhere is becoming 27/3 then 27 too large for month is becoming 1 (I.e. null). My guess is somewhere under the hood a conversion to string is happening to pass into SQL. Commented Apr 8, 2016 at 16:57

2 Answers 2

1

I am having the same issue with pymssql version 1.02. Although its not the cleanest aproach, I am using the workaround suggested by the OP and converting the string value to a python datetime object with the correct values using the dateutil.parser module. Here is the code I am using, provided that iso_datetime_string contains the string with the datetime in ISO format, as returned by the workaround:

import dateutil.parser as ps

correct_datetime_obj = ps.parse(iso_datetime_string)
Sign up to request clarification or add additional context in comments.

Comments

0

I'm still not sure what is causing this problem, but I found a solution: convert the datetime data to type varchar when the query is performed:

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

Previously I was performing this query:

select event_time from event_detail;

where event_time is of type datetime

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.