spookymodem
spookymodem

Reputation: 531

Python and SQL Server: Issue with datetime Data

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!

Upvotes: 3

Views: 2689

Answers (2)

cfragni
cfragni

Reputation: 46

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)

Upvotes: 1

spookymodem
spookymodem

Reputation: 531

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

Upvotes: 0

Related Questions