简体   繁体   English

在QDateTimeEdit中获取当前日期时间

[英]Get current datetime in QDateTimeEdit

This is my first time using Qt Designer, I create function to get datetime data and then store as string in textedit 这是我第一次使用Qt Designer,我创建了函数来获取日期时间数据,然后将其存储为字符串

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtCore import *
from PyQt5 import uic

Ui_MainWindow, QtBaseClass = uic.loadUiType("datetime2.ui")


class MyApp(QMainWindow):

    def __init__(self):
        super(MyApp,self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.GetDatetime)

    def GetDatetime(self):
        dt = self.ui.dateTimeEdit.dateTime()
        dt_string = dt.toString(self.ui.dateTimeEdit.displayFormat())
        self.ui.textEdit.setText(dt_string)

if __name__ == "__main__":
    if not QApplication.instance():
        app = QApplication(sys.argv)
    else:
        app = QApplication.instance() 
    window = MyApp()
    window.show()
    app.exec()

Here the output 这里的输出

图片1

When I change dateTimeEdit column and press button the button, the value in edit text also change. 当我更改dateTimeEdit列并按按钮时,编辑文本中的值也会更改。

My question is, how to set datetime with local time every open the program ? 我的问题是,如何在每次打开程序时使用本地时间设置日期时间? And my second question how to show the second's time, because when I ran the program, can't shown second's value ? 我的第二个问题是如何显示秒钟的时间,因为当我运行程序时,无法显示秒钟的值?

You have to have the current time using QDateTime.currentDateTime() and set it in the QDateTimeEdit using the setDateTime() method. 您必须使用QDateTime.currentDateTime()获得当前时间,并使用setDateTime()方法在QDateTimeEdit进行设置。

To show the seconds you must set a displayFormat that shows the seconds, for example: dd/MM/yyyy hh:mm:ss . 要显示秒数,必须设置一个显示秒数的displayFormat ,例如: dd/MM/yyyy hh:mm:ss

import sys
from PyQt5 import QtCore, QtWidgets, uic

Ui_MainWindow, QtBaseClass = uic.loadUiType("datetime2.ui")


class MyApp(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyApp, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.GetDatetime)
        self.ui.dateTimeEdit.setDateTime(QtCore.QDateTime.currentDateTime())
        self.ui.dateTimeEdit.setDisplayFormat("dd/MM/yyyy hh:mm:ss")

    def GetDatetime(self):
        dt = self.ui.dateTimeEdit.dateTime()
        dt_string = dt.toString(self.ui.dateTimeEdit.displayFormat())
        self.ui.textEdit.setText(dt_string)


if __name__ == "__main__":
    app = QtWidgets.QApplication.instance()
    if app is None:
        app = QtWidgets.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM