简体   繁体   中英

How to use Qt 5 datetime data to query Sqlite3 using Python3 and PyQt5

I have a Qt form with two QDateTimeEdit controls. I want to use these dates and times in the WHERE clause of a sqlite3 SELECT statement when the user presses the SEARCH button. But I can't figure out how to extract the date and time components from the QDateTime object in order to construct the julian dates that Sqlite needs.

I have spent many hours reading and rereading the Qt C++ class reference documentation that the PyQt5 Reference Guide links to and trying different things, including trying to do various conversion using QVariant but all to no avail. Seems to me that the QString QDateTime::toString(const QString &format)const method is what I need to use but PyQt5 bindings don't seem to include QString or the toString method? I came across a post that seemed to confirm that this method is what I need but it was referring to PyQt4. Is it possible that support for this method was dropped in the PyQt5 release?

According to the documentation :

The date and time functions use a subset of IS0-8601 date and time formats. The date() function returns the date in this format: YYYY-MM-DD. The time() function returns the time as HH:MM:SS. The datetime() function returns "YYYY-MM-DD HH:MM:SS" . The julianday() function returns the Julian day - the number of days since noon in Greenwich on November 24, 4714 BC (Proleptic Gregorian calendar). The strftime() routine returns the date formatted according to the format string specified as the first argument. The format string supports the most common substitutions found in the strftime() function from the standard C library plus two new substitutions, %f and %J. The following is a complete list of valid strftime() substitutions:

The time data type must have the format YYYY-MM-DD HH:MM:SS , In Qt (and therefore in PyQt) we can get it using the toString function:

QDateTime.toString("yyyy-MM-dd hh:mm:ss")

Example:

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtSql import *
import sys

def createConnection():
    db = QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName('memory')
    if not db.open():
        QMessageBox.critical(None, qApp.tr("Cannot open database"),
                             qApp.tr("Unable to establish a database connection.\n"
                                     "This example needs SQLite support. Please read "
                                     "the Qt SQL driver documentation for information "
                                     "how to build it.\n\n"
                                     "Click Cancel to exit."),
                             QMessageBox.Cancel)
        return False

    query = QSqlQuery()
    query.exec_("create table test(id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, dt DATETIME default current_timestamp)")

    query.exec_("insert into test (dt) values('2007-01-01 10:00:00')")
    query.exec_("insert into test (dt) values('2008-01-01 10:00:00')")
    query.exec_("insert into test (dt) values('2009-01-01 10:00:00')")
    query.exec_("insert into test (dt) values('2010-01-01 10:00:00')")
    return True

class Widget(QWidget):
    def __init__(self, change_cursor=True, parent=None):
        QWidget.__init__(self, parent=parent)
        layout = QHBoxLayout(self)
        self.fromDateTE = QDateTimeEdit()
        self.toDateTE = QDateTimeEdit()
        layout.addWidget(self.fromDateTE)
        layout.addWidget(self.toDateTE)
        btn = QPushButton("Select")
        layout.addWidget(btn)
        btn.clicked.connect(self.onClick)

    def onClick(self):
        _from = self.fromDateTE.dateTime().toString("yyyy-MM-dd hh:mm:ss")
        _to = self.toDateTE.dateTime().toString("yyyy-MM-dd hh:mm:ss")
        sql = "SELECT * from test WHERE dt BETWEEN datetime('{}') AND datetime('{}')".format(_from, _to)
        query = QSqlQuery(sql)
        while query.next():
            print(query.value(1))

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)

    if not createConnection():
        sys.exit(1)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

If we place the dates as shown in the following figure we get the result shown below.

Screenshot:

在此处输入图片说明

Output:

2008-01-01 10:00:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM