QDateEdit преобразовать в datetime Python
Имеется приложение с полем QDateEdit, где пользователь вводит дату, с другой стороны у меня есть функция, которая использует дату в формате datetime. Как QDateEdit можно преобразовать в datetime?
date = self.QDateEdit #Получаю дату datetime(date.dateTime())# Преобразую, но выдает ошибку
Traceback (most recent call last): File "c:\Users\deriabin_ns\Preactor\Scheduler1.py", line 150, in copy_text print(datetime(date.dateTime())) TypeError: an integer is required (got type QDateTime)
В функции использую дату в таком формате
datetime(2023, 3, 6, 8, 0, 0)
PyQt QDateTimeEdit
Summary: in this tutorial, you’ll learn how to create a date & time entry widget using the PyQt QDateTimeEdit class.
Introduction to the PyQt QDateTimeEdit widget
The QDateTimeEdit class allows you to create a widget for editing dates & times:

The QDateTimeEdit widget allows you to edit the date and time using the keyboard or up/down arrow keys to increase/decrease the value.
Also, you can use the left/right arrow key to move between the day, month, year, hour, and minute sections of the entry.
The QDateTimeEdit has the following useful methods and properties:
| Property | Description |
|---|---|
| date() | Return the date value displayed by the widget. The return type is QDate . To convert it to a datetime.date object, you use the toPyDate() method of the QDate class. |
| time() | Return the time displayed by the widget. The return value has the type of QTime . Use the toPyTime() method to convert it to a Python datetime.time object. |
| dateTime() | Return the date and time value displayed by the widget. The return type is QDateTime . |
| minimumDate | The earliest date that can be set by the user. |
| maximumDate | The latest date that can be set by the user. |
| minimumTime | The earliest time that can be set by the user. |
| maximumTime | The latest time that can be set by the user. |
| minimumDateTime | The earliest date & time that can be set by the user. |
| maximumDateTime | The latest date & time that can be set by the user. |
| calendarPopup | Display a calendar popup if it is True. |
| displayFormat | is a string that formats the date displayed in the widget. |
The QDateTimeEdit emits the editingFinished() signal when the editing is finished. If you want to trigger an action whenever the value of the QDateTimeEdit widget changes, you can connect to the dateTimeChanged() signal.
If you want to create a widget for editing dates, you can use QDateEdit . Similarly, you can use QTimeEdit to create a widget for editing times only
PyQt QDateTimeEdit widget example
The following program uses the QDateTimeEdit class to create a widget for editing date & time:
import sys from PyQt6.QtWidgets import QApplication, QWidget, QDateTimeEdit, QLabel, QFormLayout class MainWindow(QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setWindowTitle('PyQt QDateTimeEdit') self.setMinimumWidth(200) layout = QFormLayout() self.setLayout(layout) self.datetime_edit = QDateTimeEdit(self, calendarPopup=True) self.datetime_edit.dateTimeChanged.connect(self.update) self.result_label = QLabel('', self) layout.addRow('Date:', self.datetime_edit) layout.addRow(self.result_label) self.show() def update(self): value = self.datetime_edit.dateTime() self.result_label.setText(value.toString("yyyy-MM-dd HH:mm")) if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() sys.exit(app.exec())Code language: Python (python)
First, create the QDateTimeEdit widget:
self.datetime_edit = QDateTimeEdit(self, calendarPopup=True)Code language: Python (python)
Second, connect the dateTimeChanged() signal to the update() method:
self.date_edit.dateTimeChanged.connect(self.update)Code language: Python (python)
Third, create a QLabel widget to display the value of the date_edit widget once the editing is finished:
self.result_label = QLabel('', self)Code language: Python (python)
Finally, define the update() method that updates the label widget with the current value of the date & time entry:
def update(self): value = self.datetime_edit.dateTime() self.result_label.setText(value.toString("yyyy-MM-dd HH:mm"))Code language: Python (python)

Summary
- Use the QDateTimeEdit to create a date and time entry widget.
- Use the dateTime() method to get the current value of the QDateTimeEdit widget
Как работать с qdateedit python datetime
На этом шаге мы перечислим основные методы этих классов .
setDateTime () — устанавливает дату и время. В качестве параметра указывается экземпляр класса QDateTime или экземпляр класса datetime из языка Python . Метод является слотом;
dateTimeEdit.setDisplayFormat("dd.MM.yyyy HH:mm:ss")
Рис.1. Компонент QDateEdit с открытым календарем
# -*- coding: utf-8 -*- from PyQt5 import QtWidgets, QtCore import sys import datetime app = QtWidgets.QApplication(sys.argv) window = QtWidgets.QWidget() window.setWindowTitle("QDateEdit") now = datetime.datetime.now() # Получить текущую дату dateedit = QtWidgets.QDateEdit(now) # Использовать ее в конструкторе dateedit.setCalendarPopup(True) # Эта строка добавлена vbox = QtWidgets.QVBoxLayout() vbox.addWidget(dateedit) window.setLayout(vbox) window.show() sys.exit(app.exec_())
Архив с файлом можно взять здесь.
При изменении значений даты или времени генерируются сигналы timeChanged () , dateChanged () и dateTimeChanged () . Внутри обработчиков через параметр доступно новое значение.
Классы QDateEdit (поле для ввода даты) и QTimeEdit (поле для ввода времени) созданы для удобства и отличаются от класса QDateTimeEdit только форматом отображаемых данных. Эти классы наследуют методы базовых классов и не добавляют никаких своих методов.
На следующем шаге мы рассмотрим календарь .
Setting Date and Time for QDateEdit and QTimeEdit
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?
asked Sep 3, 2020 at 19:06
MrXsquared MrXsquared
32.9k 21 21 gold badges 63 63 silver badges 113 113 bronze badges
1 Answer 1
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)