Search code examples
sqlpyodbcqdatetime

How to convert qdatetime into sql datetime and select from sql table in python?


User choose the QDateTime and I need to write query in pyodbc which selects items in table which date are greater than choosen date. How to convert it in sql datetime? And how to write this request?


Solution

  • You can convert QDateTime variable (e.g. starttime) to a formatted string using something like this:

    starttime.toString("YYYY-mm-dd");
    

    Pass this to Python.

    To convert that to python's native datetime, do this:

    import datetime
    starttime = datetime.datetime.strptime(data_you_got_from_QDateTime, '%Y-%m-%d')
    

    That'll give you a Python datetime.datetime object to work with.

    If you just want to use the data provided by QDateTime in a SQL query, you could do this:

    import pyodbc
    
    yourdate = date_received_from_QDateTime
    
    cn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')
    cursor = cn.cursor()
    
    cursor.execute("select * from yourtable where yourfield > ?", yourdate)
    for row in cursor.fetchall():
        print row
    

    That should give you reasonable information to tweak the codes above to get you the information. Since I am not aware how you are sending QDateTime to Python, I cannot comment on it.