Search code examples
python-2.7pyqt4

How can I set today is date and specific time of the day in QDateTimeEdit in PyQt4?


This is the code I have written:

dt = dt or self.cal.selectedDate()
date_time_str = str(dt.toString(QtCore.Qt.DefaultLocaleShortDate)) + " 10:00:00"
now = QtCore.QDateTime.fromString(date_time_str, 'yyyy/M/d hh:mm:ss')
self.mydateTimeEdit.setDateTime(now)
self.mydateTimeEdit.setCalendarPopup(True)

but this set date time to

1/1/00 12:00AM in the myDateTimeEdit UI.

when what I wanted is to set todays date with 10:00 AM


Solution

  • The conversion to string is unnecessary, it is enough to pass it a QTime with the desired time:

    dt = dt or self.cal.selectedDate()
    now = QtCore.QDateTime(dt, QtCore.QTime(10, 0, 0))
    self.mydateTimeEdit.setDateTime(now)
    self.mydateTimeEdit.setCalendarPopup(True)