PyQt5 DateTime – Setting Date and Time for QDateEdit and QTimeEdit

datetimepyqgispyqgis-3pyqt5

Working on a QGIS plugin, I am struggling to save/load date and time values. Users can enter dates via QDateEdit widget and times via QTimeEdit widget. Values are then stored the following:

s = QgsSettings()

# Date
self.Isochrones_Date_setting = self.dlg.Isochrones_Date.date()
s.setValue("otp_plugin/Isochrones_Date", self.Isochrones_Date_setting)
    
# Time
self.Isochrones_Time_setting = self.dlg.Isochrones_Time.time()
s.setValue("otp_plugin/Isochrones_Time", self.Isochrones_Time_setting)

and shall be read by:

s = QgsSettings()

# Date
self.Isochrones_Date_setting = s.value("otp_plugin/Isochrones_Date", QtCore.QDateTime.currentDateTime())
self.dlg.Isochrones_Date.setDateTime(self.Isochrones_Date_setting)
        
# Time
self.Isochrones_Time_setting = s.value("otp_plugin/Isochrones_Time", '14:00:00')
self.dlg.Isochrones_Time.setDateTime(self.Isochrones_Time_setting)

However, loading saved values or getting default values fails. With this code I am getting the error

TypeError: setDateTime(self, Union[QDateTime, datetime.datetime]):
argument 1 has unexpected type 'QDate'

What is the correct syntax, if not .setDateTime()? Or do I need to convert QDate to some other date before? If so, how?

Best Answer

Basically you have to use .setDate() for QDateEdit and .setTime() for QTimeEdit, not .setDateTime() and convert strings to QTime via QTime.fromString() or to QDate via QDate.fromString().

But: in this case it is a little more complicated, because QtCore.QDateTime.currentDateTime()) is in QDateTime-Format. So in this case, QDateEdit, has to be set using .setDateTime() but the stored setting from QDateEdit is in QDate-Format, so .setDate() has to be used. The simplest way to combine both possibilities, is to just use a try/except statement: it will always pick the stored one, if available, and only the standard one if no stored is available.

So the code would look like:

s = QgsSettings()

# Date
self.Isochrones_Date_setting = s.value("otp_plugin/Isochrones_Date", QtCore.QDateTime.currentDateTime())
try:
    self.dlg.Isochrones_Date.setDateTime(self.Isochrones_Date_setting) # Standard value
except:
    self.dlg.Isochrones_Date.setDate(self.Isochrones_Date_setting) # Stored value
        
# Time
self.Isochrones_Time_setting = s.value("otp_plugin/Isochrones_Time", QTime.fromString('14:00:00'))
self.dlg.Isochrones_Time.setTime(self.Isochrones_Time_setting)
Related Question