Search code examples
pythonpyqt5mysql-pythonqdatetime

Subtract two QDateTime


My problem is trying to find the time difference between two different QDateTime. I can not find a function that subtracts QDateTime. Would I have to make it to a string and create a function that subtracts or make it to a list and create a function that subtracts. I also want to storage both times and the difference in a MySql database.

I know how to add and subtract seconds, days, months, and years for one QDateTime by using addSecs, addDays, etc.

Here is an example:

PyQt5.QtCore.QDateTime(2000, 1, 31, 23, 0)

PyQt5.QtCore.QDateTime(2000, 2, 1, 0, 0)

Mon Jan 31 23:00:00 2000

Tue Feb 1 00:00:00 2000

['Mon', 'Jan', '31', '23:00:00', '2000']

['Tue', 'Feb', '1', '00:00:00', '2000']

Here the code:

    def enter(self):
        self.a= self.dateTimeEdit.dateTime()
        self.b= self.dateTimeEdit_2.dateTime()
        print(self.a)
        print(self.b)
        print(self.a.toString())
        print(self.b.toString())
        print(self.a.toString().split())
        print(self.b.toString().split())

The difference should be an hour.


Solution

  • You can use the secsTo method of QDateTime:

    Returns the number of seconds from this datetime to the other datetime. If the other datetime is earlier than this datetime, the value returned is negative.

    self.a.secsTo(self.b) corresponds to subtracting self.a from self.b and should return 3600.

    Alternatively, QDateTime also has the msecsTo and daysTo methods for respectively the difference in milliseconds and in days, which you use in the same way.