PyQt QDateTimeEdit
The QDateTimeEdit widget is used to let users select and edit dates and times. In the example, let's create one QDateTimeEdit object and set it to appear as the current date and time.
QDateTimeEdit
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QDateTimeEdit, QVBoxLayout
from PyQt5.QtCore import QDateTime
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
lbl = QLabel('QTimeEdit')
datetimeedit = QDateTimeEdit(self)
datetimeedit.setDateTime(QDateTime.currentDateTime())
datetimeedit.setDateTimeRange(QDateTime(1900, 1, 1, 00, 00, 00), QDateTime(2100, 1, 1, 00, 00, 00))
datetimeedit.setDisplayFormat('yyyy. MM.dd hh:mm:ss')
vbox = QVBoxLayout()
vbox.addWidget(lbl)
vbox.addWidget(datetimeedit)
vbox.addStretch()
self.setLayout(vbox)
self.setWindowTitle('QDateTimeEdit')
self.setGeometry(300, 300, 300, 200)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
The Edit Date, Time widget (QDateTimeEdit) appears in the window.
Related course: Create Desktop Apps with Python PyQt5
Description
datetimeedit = QDateTimeEdit(self)
datetimeedit.setDateTime(QDateTime.currentDateTime())
datetimeedit.setDateTimeRange(QDateTime(1900, 1, 1, 00, 00, 00), QDateTime(2100, 1, 1, 00, 00, 00))
Use the QDateTimeEdit class to create a date, time edit widget (datetimeedit).
Enter QDateTime.currentDateTime() in the setDateTime method so that it appears as the current date and time when the program runs.
SetDateTimeRange allows you to limit the range of time you can choose.
datetimeedit.setDisplayFormat('yyyy. MM.dd hh:mm:ss')
Time using the setDisplayFormat method 'yyyy. MM.dd to appear in the form of hh:mm:ss'.
vbox = QVBoxLayout()
vbox.addWidget(lbl)
vbox.addWidget(datetimeedit)
vbox.addStretch()
self.setLayout(vbox)
Use the vertical box layout to place the Label, Date, and Time Edit widgets vertically, and set them to the layout of the entire widget.
Related course: Create Desktop Apps with Python PyQt5