I've been trying to use QCalendarWidget to select dates that I will use later.
So I've created the widget, it shows and all look well. Then I print the selected date in a textbrowser for testing, and I see the date format is bad.
This is the code relevant for this issue:
from PyQt5 import QtGui, QtCore, QtWidgets, uic
class Window(QtWidgets.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.ui = uic.loadUi('rent_creation.ui', self)
#the widgets are called calendarWidget_start_date_2 and calendarWidget_end_date_2
self.ui.activate_thescript.clicked.connect(self.activate_script)
self.show()
def activate_script(self):
global start_date
global end_date
start_date = self.ui.calendarWidget_start_date_2.selectedDate().toString()
end_date = self.ui.calendarWidget_end_date_2.selectedDate().toString()
#print data in text browser
text = "Start date: %s \n End date: %s \n" %(start_date, end_date)
self.ui.textBrowser.setText(text)
start_date = QtCore.QDate.currentDate()
end_date = QtCore.QDate.currentDate()
def run():
app = QtWidgets.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
run()
The result is:
Start date: Wed May 9 2018
End date: Tue May 15 2018
I need the date format in the result to be:
Start date: 2018-05-09
End date: 2018-05-15
Thanks for the help :)
(I'm using globals only for the example, obviously I kick them out on my real code)
You have to pass toString()
the format "yyyy-MM-dd"
:
...
start_date = self.ui.calendarWidget_start_date_2.selectedDate().toString("yyyy-MM-dd")
end_date = self.ui.calendarWidget_end_date_2.selectedDate().toString("yyyy-MM-dd")
...
Or QtCore.Qt.ISODate
:
...
start_date = self.ui.calendarWidget_start_date_2.selectedDate().toString(QtCore.Qt.ISODate)
end_date = self.ui.calendarWidget_end_date_2.selectedDate().toString(QtCore.Qt.ISODate)
...