Home » Tutorial on Date and Time in PyQt6

Tutorial on Date and Time in PyQt6

1 Year Subscription
Oracle Java Certification
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer II [1Z0-816] Practice Tests
Spring Framework Basics Video Course
Java SE 11 Programmer I [1Z0-815] Practice Tests

PyQt6 provides extensive support for handling date and time, using modules like QDate, QTime, and QDateTime from the PyQt6.QtCore module.

These classes allow you to work with dates and times, display them in widgets, and format them according to your needs.

In this tutorial, we’ll cover:

1. Working with QDate

The QDate class represents calendar dates and provides methods to manipulate and display them.

Example: Displaying the Current Date

from PyQt6.QtCore import QDate

# Get the current date
current_date = QDate.currentDate()
print("Today's date:", current_date.toString())

Output:

Today's date: Wed Nov 08 2024

Example: Creating and Manipulating Dates

from PyQt6.QtCore import QDate

# Create a specific date
specific_date = QDate(2024, 11, 8)
print("Specific date:", specific_date.toString())

# Add days
new_date = specific_date.addDays(10)
print("10 days later:", new_date.toString())

# Subtract days
earlier_date = specific_date.addDays(-10)
print("10 days earlier:", earlier_date.toString())

# Day, Month, Year
print("Day:", specific_date.day())
print("Month:", specific_date.month())
print("Year:", specific_date.year())

2. Working with QTime

The QTime class represents clock times.

Example: Displaying the Current Time

from PyQt6.QtCore import QTime

# Get the current time
current_time = QTime.currentTime()
print("Current time:", current_time.toString())

Example: Creating and Manipulating Time

from PyQt6.QtCore import QTime

# Create a specific time
specific_time = QTime(14, 30, 0)
print("Specific time:", specific_time.toString())

# Add hours and minutes
new_time = specific_time.addSecs(3600)  # Add 1 hour (3600 seconds)
print("1 hour later:", new_time.toString())

# Subtract time
earlier_time = specific_time.addSecs(-900)  # Subtract 15 minutes (900 seconds)
print("15 minutes earlier:", earlier_time.toString())

# Hour, Minute, Second
print("Hour:", specific_time.hour())
print("Minute:", specific_time.minute())
print("Second:", specific_time.second())

3. Working with QDateTime

The QDateTime class combines both date and time.

Example: Displaying Current Date and Time

from PyQt6.QtCore import QDateTime

# Get the current date and time
current_datetime = QDateTime.currentDateTime()
print("Current date and time:", current_datetime.toString())

Example: Creating and Manipulating Date and Time

from PyQt6.QtCore import QDateTime

# Create a specific date and time
specific_datetime = QDateTime(2024, 11, 8, 14, 30, 0)
print("Specific date and time:", specific_datetime.toString())

# Add days and seconds
new_datetime = specific_datetime.addDays(2).addSecs(3600)
print("2 days and 1 hour later:", new_datetime.toString())

# Subtract time
earlier_datetime = specific_datetime.addDays(-1).addSecs(-1800)
print("1 day and 30 minutes earlier:", earlier_datetime.toString())

4. Formatting Dates and Times

You can format dates and times using toString() with a format string.

Example: Formatting a Date

from PyQt6.QtCore import QDate

current_date = QDate.currentDate()
print("Default format:", current_date.toString())
print("ISO format:", current_date.toString(Qt.DateFormat.ISODate))
print("Custom format:", current_date.toString("dd/MM/yyyy"))

Output:

Default format: Wed Nov 08 2024
ISO format: 2024-11-08
Custom format: 08/11/2024

Example: Formatting a Time

from PyQt6.QtCore import QTime

current_time = QTime.currentTime()
print("Default format:", current_time.toString())
print("Custom format:", current_time.toString("hh:mm:ss A"))

Output:

Default format: 14:30:45
Custom format: 02:30:45 PM

5. Using QDateEdit, QTimeEdit, and QDateTimeEdit Widgets

PyQt6 provides widgets to allow users to select dates, times, or both.

Example: Using QDateEdit

from PyQt6.QtWidgets import QApplication, QMainWindow, QDateEdit
from PyQt6.QtCore import QDate

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("QDateEdit Example")
    window.setGeometry(100, 100, 300, 200)

    date_edit = QDateEdit(window)
    date_edit.setDate(QDate.currentDate())
    date_edit.setGeometry(50, 50, 150, 30)
    date_edit.setCalendarPopup(True)  # Enables a calendar popup

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Example: Using QTimeEdit

from PyQt6.QtWidgets import QApplication, QMainWindow, QTimeEdit
from PyQt6.QtCore import QTime

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("QTimeEdit Example")
    window.setGeometry(100, 100, 300, 200)

    time_edit = QTimeEdit(window)
    time_edit.setTime(QTime.currentTime())
    time_edit.setGeometry(50, 50, 150, 30)

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Example: Using QDateTimeEdit

from PyQt6.QtWidgets import QApplication, QMainWindow, QDateTimeEdit
from PyQt6.QtCore import QDateTime

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("QDateTimeEdit Example")
    window.setGeometry(100, 100, 300, 200)

    datetime_edit = QDateTimeEdit(window)
    datetime_edit.setDateTime(QDateTime.currentDateTime())
    datetime_edit.setGeometry(50, 50, 200, 30)
    datetime_edit.setCalendarPopup(True)

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

6. Practical Example: Digital Clock

from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt6.QtCore import QTimer, QTime, Qt

def update_time(label):
    current_time = QTime.currentTime().toString("hh:mm:ss")
    label.setText(current_time)

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("Digital Clock")
    window.setGeometry(100, 100, 300, 100)

    label = QLabel("", window)
    label.setAlignment(Qt.AlignmentFlag.AlignCenter)
    label.setStyleSheet("font-size: 24px;")
    label.setGeometry(50, 20, 200, 50)

    timer = QTimer()
    timer.timeout.connect(lambda: update_time(label))
    timer.start(1000)  # Update every second

    update_time(label)
    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Output:

  • A real-time clock displays the current time, updating every second.

Summary

In this tutorial, we covered:

  1. QDate, QTime, and QDateTime Basics: Creating, manipulating, and displaying date/time.
  2. Formatting: Customizing date/time formats.
  3. Interactive Widgets: Using QDateEdit, QTimeEdit, and QDateTimeEdit.
  4. Practical Example: Building a digital clock.

PyQt6 provides robust tools for handling dates and times, making it ideal for building calendars, schedulers, or time-sensitive applications. Mastering these components will greatly enhance your PyQt6 GUIs.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More