PyQt5具有QDate,QDateTime,QTime类来处理日期和时间。 QDate是用于使用公历中的日历日期的类。 它具有确定日期,比较或处理日期的方法。 QTime类使用时钟时间。 它提供了比较时间,确定时间的方法以及其他各种时间操纵方法。 QDateTime是将QDate和QTime对象都组合到一个对象中的类。
1. 当前日期和时间
PyQt5具有currentDate(),currentTime()和currentDateTime()方法来确定当前日期和时间。
#fileName: current_date_time.py
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))
2.UTC时间
#fileName: utc_local.py
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()))
3.计算天数差异
#fileName: xmas.py
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))
4.日期时间算法
#fileName:arithmetic.py
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 seconds:{0}".format(now.addSecs(3).toString(Qt.ISODate)))
print("Adding 12 seconds:{0}".format(now.addSecs(12).toString(Qt.ISODate)))
5.夏令时
#fineName: daylight_saving.py
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")
6.Unix时间
#fileName: unix_time.py
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))
7.朱利安日
#fileName: julian_day.py
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())
8.历史战役
#fileName: battles.py
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))
参考网址: