MySQL TIMESTAMP to QDateTime with milliseconds

后端 未结 2 858
既然无缘
既然无缘 2020-12-20 12:16

If I use a QSqlTableModel to access a MySQL database I can convert a TIMESTAMP field using the following:

QDateTime dateTime = index(section, column).data().         


        
相关标签:
2条回答
  • 2020-12-20 12:57

    From this page:

    https://dev.mysql.com/doc/refman/5.6/en/datetime.html

    A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision. In particular, as of MySQL 5.6.4, any fractional part in a value inserted into a DATETIME or TIMESTAMP column is stored rather than discarded.

    So, the millisecond is there in MySQL! But the query.value() does not get it - at this point in the Qt history as pointed by @peppe here.

    Relating back to the original question: There is no proper way to see the millisecond since the query does not have it. One alternative could be to modify the query, from:

    SELECT timestamp FROM table;
    

    to

    SELECT DATE_FORMAT(timestamp, '%Y-%c-%e %H:%i:%s.%f') as timestamp FROM table;
    

    And then finish the job with:

    QString str = query.value(column).toString();
    QDateTime dateTime = QDateTime::fromString(str, "yyyy-MM-dd hh:mm:ss.zzz000");
    

    I got the insight from here.

    0 讨论(0)
  • 2020-12-20 13:05

    From MySQL 5.1 documentation:

    A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision. Although this fractional part is recognized, it is discarded from values stored into DATETIME or TIMESTAMP columns.

    It seems like seconds is the best you can do with timestamp.

    0 讨论(0)
提交回复
热议问题