PyQt6 date and time
QDate, QTime, QDateTime
PyQt6 has QDate
, QDateTime
, QTime
classes to handle dates and times. QDate
is a class for working with dates in the Gregorian calendar. It has methods to get, compare or manipulate dates. QTime
class for handling time. It provides methods for comparing times, determining times, and various other time manipulations. QDateTime
is a combination of QDate
and QTime
.
PyQt current date and time
PyQt6 has currentDate
, currentTime
and currentDateTime
methods to get the current date or time.
# file: current_date_time.py
#!/usr/bin/python
from PyQt6.QtCore import QDate, QTime, QDateTime, Qt
now = QDate.currentDate()
print(now.toString(Qt.DateFormat.ISODate))
print(now.toString(Qt.DateFormat.RFC2822Date))
datetime = QDateTime.currentDateTime()
print(datetime.toString())
time = QTime.currentTime()
print(time.toString(Qt.DateFormat.ISODate))
The above code prints out the current date, current date and time, time in different formats.
now = QDate.currentDate()
currentDate
method returns the current date.
print(now.toString(Qt.DateFormat.ISODate))
print(now.toString(Qt.DateFormat.RFC2822Date))
Pass toString
in different parameters to : Qt.DateFormat.ISODate
and Qt.DateFormat.RFC2822Date
to get dates in different formats.
datetime = QDateTime.currentDateTime()
currentDateTime
method returns the current date and time.
time = QTime.currentTime()
currentTime
method returns the current time.
$ ./current_date_time.py
2021-04-23
23 Apr 2021
Fri Apr 23 11:41:39 2021
11:41:39
PyQt6 UTC time
Our planet is a sphere, rotating around its own axis. The Earth rotates eastward, so the sun rises in different places at different times. The Earth rotates about once every 24 hours. Therefore, the world is divided into 24 time zones. In each time zone, there is a different local time. Local time is usually further modified by daylight saving time.
In fact, a standard time is also required. A standard time helps avoid time zone and daylight savings confusion. UTC (Universal Coordinated Time) is chosen as the primary time standard. UTC time is used in aviation, weather forecasts, flight plans, air traffic control clearances, and maps. Unlike local time, UTC time does not change with the seasons.
# file: utc_local.py
#!/usr/bin/python
from PyQt6.QtCore import QDateTime, Qt
now = QDateTime.currentDateTime()
print('Local datetime: ', now.toString(Qt.DateFormat.ISODate))
print('Universal datetime: ', now.toUTC().toString(Qt.DateFormat.ISODate))
print(f'The offset from UTC is: {
now.offsetFromUtc()} seconds')
本例获取了标准时间和本地时间。
print('Local datetime: ', now.toString(Qt.DateFormat.ISODate))
currentDateTime
method returns the current time in local time. We can use toLocalTime
the method to convert standard time to local time.
print('Universal datetime: ', now.toUTC().toString(Qt.DateFormat.ISODate))
We toUTC
get the standard time from the time object using the method.
print(f'The offset from UTC is: {
now.offsetFromUtc()} seconds')
offsetFromUtc
method gives the difference between local time and standard time in seconds.
$ ./utc_local.py
Local datetime: 2021-04-23T11:44:15
Universal datetime: 2021-04-23T09:44:15Z
The offset from UTC is: 7200 seconds
PyQt6 days
daysInMonth
The method returns the number of days in the specified month, and daysInYear
the method returns the number of days in the specified year.
# file: n_of_days.py
#!/usr/bin/python
from PyQt6.QtCore import QDate
now = QDate.currentDate()
d = QDate(1945, 5, 7)
print(f'Days in month: {
d.daysInMonth()}')
print(f'Days in year: {
d.daysInYear()}')
This example prints the number of days in the specified year and month.
$ ./n_of_days.py
Days in month: 31
Days in year: 365
PyQt6 days difference
daysTo
method returns the difference from one date to another.
# file: xmas.py
#!/usr/bin/python
from PyQt6.QtCore import QDate, Qt
now = QDate.currentDate()
y = now.year()
print(f'today is {
now.toString(Qt.DateFormat.ISODate)}')
xmas1 = QDate(y-1, 12, 25)
xmas2 = QDate(y, 12, 25)
dayspassed = xmas1.daysTo(now)
print(f'{
dayspassed} days have passed since last XMas')
nofdays = now.daysTo(xmas2)
print(f'There are {
nofdays} days until next XMas')
This example calculates the number of days from the previous Christmas to the next Christmas.
$ ./xmas.py
today is 2021-04-23
119 days have passed since last XMas
There are 246 days until next XMas
Calculation of PyQt6 time
We often need to perform calculations such as adding and subtracting days, seconds or years.
# file: arithmetic.py
#!/usr/bin/python
from PyQt6.QtCore import QDateTime, Qt
now = QDateTime.currentDateTime()
print(f'Today: {
now.toString(Qt.DateFormat.ISODate)}')
print(f'Adding 12 days: {
now.addDays(12).toString(Qt.DateFormat.ISODate)}')
print(f'Subtracting 22 days: {
now.addDays(-22).toString(Qt.DateFormat.ISODate)}')
print(f'Adding 50 seconds: {
now.addSecs(50).toString(Qt.DateFormat.ISODate)}')
print(f'Adding 3 months: {
now.addMonths(3).toString(Qt.DateFormat.ISODate)}')
print(f'Adding 12 years: {
now.addYears(12).toString(Qt.DateFormat.ISODate)}')
This example shows adding or subtracting days, seconds, months, or years to the current datetime.
$ ./arithmetic.py
Today: 2021-04-23T12:06:10
Adding 12 days: 2021-05-05T12:06:10
Subtracting 22 days: 2021-04-01T12:06:10
Adding 50 seconds: 2021-04-23T12:07:00
Adding 3 months: 2021-07-23T12:06:10
Adding 12 years: 2033-04-23T12:06:10
PyQt6 daylight saving time
Daylight Saving Time (DST) is the time shift forward during the summer, making the nights longer. In early spring, the time is adjusted forward by one hour, and in autumn, it is adjusted back to standard time.
# file: daylight_saving.py
#!/usr/bin/python
from PyQt6.QtCore import QDateTime, QTimeZone, Qt
now = QDateTime.currentDateTime()
print(f'Time zone: {
now.timeZoneAbbreviation()}')
if now.isDaylightTime():
print('The current date falls into DST time')
else:
print('The current date does not fall into DST time')
This example determines whether a time is in daylight saving time.
print(f'Time zone: {
now.timeZoneAbbreviation()}')
timeZoneAbbreviation
method returns the time zone abbreviation.
if now.isDaylightTime():
...
isDaylightTime
Determine if the date is in daylight saving time.
$ ./daylight_saving.py
Time zone: CEST
The current date falls into DST time
The current date belongs to daylight saving time, which is observed in the central European city of Bratislava in summer. Central European Summer Time (CEST) is 2 hours ahead of Universal Time. This time zone is a daylight saving time zone and is used in Europe and Antarctica.
PyQt6 unix epoch
An epoch is an instant in time chosen as the origin of a particular epoch. For example, in Western Christian countries, the epoch begins on the 0th day of Jesus' birth. Another example is the French Republican calendar which uses twelve years. This era was the beginning of the Republic Era, when the First Republic was proclaimed on September 22, 1792, and the monarchy was abolished.
Computers have their time too. One of the most popular eras is the Unix era. The Unix epoch is January 1, 1970 at 00:00:00 UTC (or 1970-01-01T00:00:00Z for ISO 8601). Dates and times in a computer are determined by the number of seconds or clock ticks that have passed since the epoch defined by that computer or platform.
Unix time is the number of seconds elapsed since the Unix epoch.
$ date +%s
1619172620
Unix date command can be used to get Unix time. At this particular moment, 1619172620 seconds have passed since the Unix epoch.
# file: unix_time.py
#!/usr/bin/python
from PyQt6.QtCore import QDateTime, Qt
now = QDateTime.currentDateTime()
unix_time = now.toSecsSinceEpoch()
print(unix_time)
d = QDateTime.fromSecsSinceEpoch(unix_time)
print(d.toString(Qt.DateFormat.ISODate))
This example shows the Unix time and converts it to QDateTime
.
now = QDateTime.currentDateTime()
First get the current date and time.
unix_time = now.toSecsSinceEpoch()
toSecsSinceEpoch
The Unix time is returned.
d = QDateTime.fromSecsSinceEpoch(unix_time)
Use fromSecsSinceEpoch
the method to convert Unix time to QDateTime
.
$ ./unix_time.py
1619172679
2021-04-23T12:11:19
PyQt6 Julian day
A Julian day is the number of consecutive days since the beginning of the Julian period. It is mainly used by astronomers. It should not be confused with the Julian calendar. It began in 4713 BC. Day 0 is the day at noon on January 1, 4713 BC.
The Julian Day Number (JDN) is the number of days that have passed since the period began. The Julian date (JD) at any moment is the number of Julian days at the previous noon plus the fraction of the day since that moment. (Qt does not calculate this fraction.) In addition to astronomy, Julian dates are often used by military and mainframe programs.
# file: julian_day.py
#!/usr/bin/python
from PyQt6.QtCore import QDate, Qt
now = QDate.currentDate()
print('Gregorian date for today:', now.toString(Qt.DateFormat.ISODate))
print('Julian day for today:', now.toJulianDay())
In this example, we get today's representation in the Gregorian calendar and the Julian day representation.
print('Julian day for today:', now.toJulianDay())
toJulianDay()
Returns the Julian day date.
$ ./julian_day.py
Gregorian date for today: 2021-04-23
Julian day for today: 2459328
historical battle
Calculations spanning centuries are possible using Julian days.
# file: battles.py
#!/usr/bin/python
from PyQt6.QtCore import QDate, Qt
borodino_battle = QDate(1812, 9, 7)
slavkov_battle = QDate(1805, 12, 2)
now = QDate.currentDate()
j_today = now.toJulianDay()
j_borodino = borodino_battle.toJulianDay()
j_slavkov = slavkov_battle.toJulianDay()
d1 = j_today - j_slavkov
d2 = j_today - j_borodino
print(f'Days since Slavkov battle: {
d1}')
print(f'Days since Borodino battle: {
d2}')
This example calculates the number of days elapsed since two historical events.
borodino_battle = QDate(1812, 9, 7)
slavkov_battle = QDate(1805, 12, 2)
Here are two Napoleonic battle dates.
j_today = now.toJulianDay()
j_borodino = borodino_battle.toJulianDay()
j_slavkov = slavkov_battle.toJulianDay()
It is Julian day today and the battles of Slavkov and Borodino.
d1 = j_today - j_slavkov
d2 = j_today - j_borodino
This is the difference in days between the two wars.
$ ./battles.py
Days since Slavkov battle: 78670
Days since Borodino battle: 76199
When we run this script, 78670 days have passed since the Battle of Slavkov and 76199 days have passed since the Battle of Borodino.
In this part of the PyQt6 tutorial we work with dates and times.