PyQt5 date and time

This part of the PyQt5 tutorial shows how to work with date and time in PyQt5.

QDate, QTime, QDateTime

PyQt5 has QDate, QDateTime, QTime classes to work with date and time. The QDate is a class for working with a calendar date in the Gregorian calendar. It has methods for determining the date, comparing, or manipulating dates. The QTime class works with a clock time. It provides methods for comparing time, determining the time and various other time manipulating methods. The QDateTime is a class that combines both QDate and QTime objects into one object.

Current date and time

PyQt5 has currentDate(), currentTime() and currentDateTime() methods for determining current date and time.

current_date_time.py
#!/usr/bin/python3

from PyQt5.QtCore import QDate, QTime, QDateTime, Qt

now = QDate.currentDate()

print(now.toString(Qt.ISODate))
print(now.toString(Qt.DefaultLocaleLongDate))

datetime = QDateTime.currentDateTime()

print(datetime.toString())

time = QTime.currentTime()

print(time.toString(Qt.DefaultLocaleLongDate))

The example prints the current date, date and time, and time in various formats.

now = QDate.currentDate()

The currentDate() method returns the current date.

print(now.toString(Qt.ISODate))
print(now.toString(Qt.DefaultLocaleLongDate))

The date is printed in two different formats by passing the values Qt.ISODate and Qt.DefaultLocaleLongDate to the toString() method.

datetime = QDateTime.currentDateTime()

The currentDateTime() returns the current date and time.

time = QTime.currentTime()

Finally, the currentTime() method returns the current time.

$ ./current_date_time.py 
2017-09-11
Monday, September 11, 2017
Mon Sep 11 12:37:45 2017
12:37:45 PM CEST

This is the output.

UTC time

Our planet is a sphere; it revolves round its axis. The Earth rotates towards the east, so the Sun rises at different times in different locations. The Earth rotates once in about 24 hours. Therefore, the world was divided into 24 time zones. In each time zone, there is a different local time. This local time is often further modified by the daylight saving.

There is a pragmatic need for one global time. One global time helps to avoid confusion about time zones and daylight saving time. The UTC (Universal Coordinated time) was chosen to be the primary time standard. UTC is used in aviation, weather forecasts, flight plans, air traffic control clearances, and maps. Unlike local time, UTC does not change with a change of seasons.

utc_local.py
#!/usr/bin/python3

from PyQt5.QtCore import QDateTime, Qt

now = QDateTime.currentDateTime()

print("Local datetime: ", now.toString(Qt.ISODate))
print("Universal datetime: ", now.toUTC().toString(Qt.ISODate))

print("The offset from UTC is: {0} seconds".format(now.offsetFromUtc()))

The example determines the current universal and local date and time.

print("Local datetime: ", now.toString(Qt.ISODate))

The currentDateTime() method returns the current date and time expressed as local time. We can use the toLocalTime() to convert a universal time into a local time.

print("Universal datetime: ", now.toUTC().toString(Qt.ISODate))

We get the universal time with the toUTC() method from the date time object.

print("The offset from UTC is: {0} seconds".format(now.offsetFromUtc()))

The offsetFromUtc() gives the difference between universal time and local time in seconds.

$ ./utc_local.py 
Local datetime:  2017-09-11T13:01:58
Universal datetime:  2017-09-11T11:01:58Z
The offset from UTC is: 7200 seconds

This is the output.

Number of days

The number of days in a particular month is returned by the daysInMonth() method and the number of days in a year by the daysInYear() method.

days.py
#!/usr/bin/python3

from PyQt5.QtCore import QDate, Qt

now = QDate.currentDate()

d = QDate(1945, 5, 7)

print("Days in month: {0}".format(d.daysInMonth()))
print("Days in year: {0}".format(d.daysInYear()))

The example prints the number of days in a month and year for the chosen date.

$ ./days.py 
Days in month: 31
Days in year: 365

This is the output.

Difference in days

The daysTo() method returns the number of days from a date to another date.

xmas.py
#!/usr/bin/python3

from PyQt5.QtCore import QDate

xmas1 = QDate(2016, 12, 24)
xmas2 = QDate(2017, 12, 24)

now = QDate.currentDate()

dayspassed = xmas1.daysTo(now)
print("{0} days have passed since last XMas".format(dayspassed))

nofdays = now.daysTo(xmas2)
print("There are {0} days until next XMas".format(nofdays))

The example calculates the number of days passed from the last XMas and the number of days until the next XMas.

$ ./xmas.py 
261 days have passed since last XMas
There are 104 days until next XMas

This is the output.

Datetime arithmetic

We often need to add or subtract days, seconds, or years to a datetime value.

arithmetic.py
#!/usr/bin/python3

from PyQt5.QtCore import QDateTime, Qt

now = QDateTime.currentDateTime()

print("Today:", now.toString(Qt.ISODate))
print("Adding 12 days: {0}".format(now.addDays(12).toString(Qt.ISODate)))
print("Subtracting 22 days: {0}".format(now.addDays(-22).toString(Qt.ISODate)))

print("Adding 50 seconds: {0}".format(now.addSecs(50).toString(Qt.ISODate)))
print("Adding 3 months: {0}".format(now.addMonths(3).toString(Qt.ISODate)))
print("Adding 12 years: {0}".format(now.addYears(12).toString(Qt.ISODate)))

The example determines the current datetime and add or subtract days, seconds, months, and years.

$ ./arithmetics.py 
Today: 2017-09-11T13:15:24
Adding 12 days: 2017-09-23T13:15:24
Subtracting 22 days: 2017-08-20T13:15:24
Adding 50 seconds: 2017-09-11T13:16:14
Adding 3 months: 2017-12-11T13:15:24
Adding 12 years: 2029-09-11T13:15:24

This is the example output.

Daylight saving time

Daylight saving time (DST) is the practice of advancing clocks during summer months so that evening daylight lasts longer. The time is adjusted forward one hour in the beginning of spring and adjusted backward in the autumn to standard time.

daylight_saving.py
#!/usr/bin/python3

from PyQt5.QtCore import QDateTime, QTimeZone, Qt

now = QDateTime.currentDateTime()

print("Time zone: {0}".format(now.timeZoneAbbreviation()))

if now.isDaylightTime():
    print("The current date falls into DST time")
else:
    print("The current date does not fall into DST time")

The example checks if the datetime is in the daylight saving time.

print("Time zone: {0}".format(now.timeZoneAbbreviation()))

The timeZoneAbbreviation() method returns the time zone abbreviation for the datetime.

if now.isDaylightTime():

The isDaylightTime() returns if the datetime falls in daylight saving time.

$ ./daylight_saving.py 
Time zone: CEST
The current date falls into DST time

The current date falls into DST time The program was executed in Bratislava, which is a city in Central Europe, during summer. Central European Summer Time (CEST) is 2 hours ahead of universtal time. This time zone is a daylight saving time time zone and is used in Europe and Antarctica. The standard time, which is used in winter, is Central European Time (CET).

Unix epoch

An epoch is an instant in time chosen as the origin of a particular era. For example in western Christian countries the time epoch starts from day 0, when Jesus was born. Another example is the French Republican Calendar which was used for twelve years. The epoch was the beginning of the Republican Era which was proclaimed on September 22, 1792, the day the First Republic was declared and the monarchy abolished.

Computers have their epochs too. One of the most popular is the Unix epoch. The Unix epoch is the time 00:00:00 UTC on 1 January 1970 (or 1970- 01-01T00:00:00Z ISO 8601). The date and time in a computer is determined according to the number of seconds or clock ticks that have elapsed since the defined epoch for that computer or platform.

Unix time is the number of seconds elapsed since Unix epoch.

$ date +%s
1505128973

Unix date command can be used to get the Unix time. At this particular moment, 1505128973 seconds have passed since the Unix epoch.

unix_time.py
#!/usr/bin/python3

from PyQt5.QtCore import QDateTime, Qt

now = QDateTime.currentDateTime()

unix_time = now.toSecsSinceEpoch() 
print(unix_time)

d = QDateTime.fromSecsSinceEpoch(unix_time)
print(d.toString(Qt.ISODate))

The example prints the Unix time and converts it back to the QDateTime.

now = QDateTime.currentDateTime()

First, we retrieve the current date and time.

unix_time = now.toSecsSinceEpoch() 

The toSecsSinceEpoch() returns the Unix time.

d = QDateTime.fromSecsSinceEpoch(unix_time)

With the fromSecsSinceEpoch() we convert the Unix time to QDateTime.

$ ./unix_time.py 
1505129851
2017-09-11T13:37:31

This is the output.

Julian day

Julian day refers to a continuous count of days since the beginning of the Julian Period. It is used primarily by astronomers. It should not be confused with the Julian calendar. The Julian Period started in 4713 BC. The Julian day number 0 is assigned to the day starting at noon on January 1, 4713 BC.

The Julian Day Number (JDN) is the number of days elapsed since the beginning of this period. The Julian Date (JD) of any instant is the Julian day number for the preceding noon plus the fraction of the day since that instant. (Qt does not compute this fraction.) Apart from astronomy, Julian dates are often used by military and mainframe programs.

julian_day.py
#!/usr/bin/python3

from PyQt5.QtCore import QDate, Qt

now = QDate.currentDate()

print("Gregorian date for today: ", now.toString(Qt.ISODate))
print("Julian day for today: ", now.toJulianDay()) 

In the example, we compute the Gregorian date and the Julian day for today.

print("Julian day for today: ", now.toJulianDay())

The Julian day is returned with the toJulianDay() method.

$ ./julianday.py 
Gregorian date for today:  2017-09-11
Julian day for today:  2458008

This is the output.

Historical battles

With Julian day it is possible to do calculations that span centuries.

battles.py
#!/usr/bin/python3

from PyQt5.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("Days since Slavkov battle: {0}".format(d1))
print("Days since Borodino battle: {0}".format(d2))

The example counts the number of days passed since two historical events.

borodino_battle = QDate(1812, 9, 7)
slavkov_battle = QDate(1805, 12, 2)

We have two dates of battles of the Napoleonic era.

j_today = now.toJulianDay()
j_borodino = borodino_battle.toJulianDay()
j_slavkov = slavkov_battle.toJulianDay()

We compute the Julian days for today and for the Battles of Slavkov and Borodino.

d1 = j_today - j_slavkov
d2 = j_today - j_borodino

We compute the number of days passed since the two battles.

$ ./battles.py 
Days since Slavkov battle: 77350
Days since Borodino battle: 74879

When we run this script, 77350 days have passed since the Slavkov battle, and 74878 since the Borodino battle.

In this part of the PyQt5 tutorial, we have worked with date and time.