Search code examples
pythondatetimetimetimestamppyqt4

Converting timestamp into QDateEdit and the opposite


I have created a QWidget and I want to convert a timestamp and put the date into a QDateEdit by pressing the set button. And get the value from QDateEdit, convert it into a timestamp and put it into the QLabel by pressing the print button. So far so good, but if I get the timestamp that is created from QDateEdit and place it into the QLineEdit and start over, I can see that I am missing a day. What is wrong ?

For example:

Input: 1532386800.0 >>> into QDateEdit (set button): 23/07/2018 >>> output(print button):1532300400.0

Input: 1532300400.0 >>> into QDateEdit: 22/07/2018 >>> output:1532214000.0

Input: 1532214000.0 >>> into QDateEdit: 21/07/2018 >>> output:1532127600.0

Every time that I am converting from timestamp to date and then date back into timestamp I am losing one day. I found the same issue in some online conversion webpages as well.

I think that problem is on time. When you get the date from QDateEdit the time is 00:00:00

enter image description here

from PyQt4 import QtCore, QtGui
import time
import datetime

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(object):

    inputDateFormat = "yyyy-MM-dd"
    outputDateFormat = "dd/MM/yyyy"


    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(400, 300)
        self.dateEdit = QtGui.QDateEdit(Form)
        self.dateEdit.setGeometry(QtCore.QRect(40, 120, 110, 27))
        self.dateEdit.setObjectName(_fromUtf8("dateEdit"))
        self.print_btn = QtGui.QPushButton(Form)
        self.print_btn.setGeometry(QtCore.QRect(190, 120, 98, 27))
        self.print_btn.setObjectName(_fromUtf8("print_btn"))
        self.set_btn = QtGui.QPushButton(Form)
        self.set_btn.setGeometry(QtCore.QRect(190, 90, 98, 27))
        self.set_btn.setObjectName(_fromUtf8("set_btn"))
        self.date_input = QtGui.QLineEdit(Form)
        self.date_input.setGeometry(QtCore.QRect(10, 90, 171, 27))
        self.date_input.setObjectName(_fromUtf8("date_input"))
        self.label = QtGui.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(30, 190, 81, 16))
        self.label.setObjectName(_fromUtf8("label"))
        self.timestamp = QtGui.QLabel(Form)
        self.timestamp.setGeometry(QtCore.QRect(120, 190, 120, 17))
        self.timestamp.setObjectName(_fromUtf8("timestamp"))

        self.retranslateUi(Form)
        QtCore.QObject.connect(self.print_btn, QtCore.SIGNAL(_fromUtf8("clicked()")), self.printTimestamp)
        QtCore.QObject.connect(self.set_btn, QtCore.SIGNAL(_fromUtf8("clicked()")), self.setTime)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.print_btn.setText(_translate("Form", "print", None))
        self.set_btn.setText(_translate("Form", "set", None))
        self.date_input.setText(_translate("Form", "1532386800.0", None))    # 946684800.0    
#        self.date_input.setText(_translate("Form", "2018-07-24 19:24:11.272000", None))
        self.label.setText(_translate("Form", "Timestamp:", None))
        self.timestamp.setText(_translate("Form", "123456", None))

    def setTime(self):

        obj = self.dateEdit

#        f = '%Y-%m-%d %H:%M:%S'
#        time.strftime(f, now)


        # This is how to get a date from QDateEdit Element        
        pyDate = obj.date().getDate()   # obj.date().toPyDate()    returns a tuple(read only list)
        pyDatetime = obj.dateTime().toPyDateTime()      # datetime() returns QDateTime, toPyDateTime() converts to datetime.datetime

        # This is how to put a date into QDateEdit Element
#        a = '2018-07-24 19:24:11.272000'
        stamp = float(self.date_input.text())
        tmToDate = datetime.datetime.utcfromtimestamp(stamp).strftime('%Y-%m-%d %H:%M:%S')
        print tmToDate 
        aCustomersDate = tmToDate.split(" ")[0]
        d = QtCore.QDate.fromString(aCustomersDate, self.inputDateFormat)
        date = d.toPyDate()                            


        # Get the current date
        newDate = QtCore.QDateTime.currentDateTime()
        pyToday = newDate.toPyDateTime()
#        newDate =QtCore.QDate.currentDate() 
#        pyToday = newDate.toPyDate()

#        formalDate = obj.date().toString(self.outputDateFormat)     # Returns QString
        formalDate = obj.dateTime().toPyDateTime()
        print 'PyDate(input): %s, pyDateTime: %s, Date: %s'%(pyDate, pyToday, formalDate)

        output = formalDate 

        obj.setDate(date)

    def printTimestamp(self):

        obj = self.dateEdit
#        formalDate = str( obj.date().toString(self.outputDateFormat) )     
        formalDate = obj.dateTime().toPyDateTime().strftime('%d/%m/%Y %H:%M:%S')  # Returns datetime.datetime
        print formalDate

        tstamp = str( time.mktime(datetime.datetime.strptime(formalDate, "%d/%m/%Y %H:%M:%S").timetuple()) )

        print tstamp
        self.timestamp.setText(tstamp)


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Form = QtGui.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

Solution

  • All this with time, datetime, QDate was little bit comfusing, but at the end I found what was the problem. I was converting from timestamp to QDate and from QDate to timestamp in different timezones. Finaly, this is the SOLUTION using local timezone conversion:

    class Ui_Form(object):
        ...
    
        def setTime(self):
    
            # This is how to put a date into QDateEdit Element using a timestamp
    #        aTime = '2018-07-24 19:24:11.272000'
            unix_timestamp = float(self.date_input.text())
    #        tmToDate = datetime.datetime.utcfromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
    #        utc_time = time.gmtime(unix_timestamp)
            local_datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(unix_timestamp))   # converts timestampt to local time and apply the format 
            local_date = local_datetime.split(" ")[0]   # get only the date
            d = QtCore.QDate.fromString(local_date, "yyyy-MM-dd")   # Convert date into QDate object
    
            self.dateEdit.setDate(d)
    
        def printTimestamp(self):
    
            # This is how to get a date from QDateEdit Element        
    #        pyDate_str = self.dateEdit.date().toString(self.outputDateFormat)    # Returns QString   
    #        pyDate = self.dateEdit.date().toPyDate()
    #        date = self.dateEdit.date().getDate()
            pyDatetime = self.dateEdit.dateTime().toPyDateTime()      # dateTime() returns QDateTime, toPyDateTime() converts to datetime.datetime
    
            formalDate = pyDatetime.strftime('%d/%m/%Y %H:%M:%S')  # Returns datetime.datetime        
            tstamp = time.mktime(datetime.datetime.strptime(formalDate, '%d/%m/%Y %H:%M:%S').timetuple())
    
            self.timestamp.setText(str(tstamp))