python設計透明電子時鐘,包含顯示當前時間、計算時間差的方法!
阿新 • • 發佈:2018-11-10
效果:
摘要
在使用Python寫程式時,經常需要輸出系統的當前時間以及計算兩個時間之間的差值,或者將當前時間加減一定時間(天數、小時、分鐘、秒)來得到新的時間,這篇文章就對一些常見的時間相關的問題系統的進行總結。
包
這裡主要使用Python的datetime包實現上述功能。
1.輸出當前系統時間
輸出結果從總到右分別為Year、Month、Day、Hour、Minute、Second,最後一個MicroSeconds就不用管了。
2.標準化輸出方法strftime()
其中:
%Y : 表示年
%m(小寫):表示月
%d(小寫):表示日
%H:表示小時
%M:表示分鐘
%S:表示秒
3.也可以只輸出年、月
4.計算兩個日期間的間隔
5.計算當前時間加減一定時間(天數、小時、分鐘、秒)
上述分別表示減去40天43分鐘和加上4小時120秒。
Python視窗pyqt5原始碼:
from PyQt5.QtWidgets import QLCDNumber from PyQt5.Qt import QPoint, QPalette, QTimer, QTime, QRect from PyQt5.QtCore import Qt class DigitalClock(QLCDNumber): def __init__(self, Parent=None): ''' Constructor ''' super().__init__(Parent) self.__InitData() #初始化類的資料 self.__InitView() #初始化介面 def __InitData(self): #初始化資料 self.__ShowColon = True #是否顯示時間如[12:07]中的冒號,用於冒號的閃爍 self.__dragPosition = QPoint(0,0) #用於儲存滑鼠相對於電子時鐘左上角的偏移值 self.__timer = QTimer(self) #新建一個定時器 #關聯timeout訊號和showTime函式,每當定時器過了指定時間間隔,就會呼叫showTime函式 self.__timer.timeout.connect(self.showTime) self.__timer.start(1000) #設定定時間隔為1000ms即1s,並啟動定時器 def __InitView(self): #初始化介面 palette = QPalette() #新建調色盤 palette.setColor(QPalette.Window, Qt.blue) #將調色盤中的窗體背景色設定為藍色 self.setPalette(palette) #在本窗體載入此調色盤 self.setWindowFlags(Qt.FramelessWindowHint) #設定窗體為無邊框模式 self.setWindowOpacity(0.5) #設定窗體的透明度為0.5 self.resize(200,60) #設定介面尺寸,寬150px,高60px self.setNumDigits(8) #允許顯示8個字元 原因,自己數右邊幾個字元 【HH:MM:SS】 self.showTime() #初始化時間的顯示 def showTime(self): #更新時間的顯示 time = QTime.currentTime() #獲取當前時間 time_text = time.toString(Qt.DefaultLocaleLongDate) #獲取HH:MM:SS格式的時間 #冒號閃爍 if self.__ShowColon == True: self.__ShowColon = False else: time_text = time_text.replace(':',' ') self.__ShowColon = True self.display(time_text) #顯示時間 def mousePressEvent(self, mouseEvent): #滑鼠按下事件 btn_code = mouseEvent.button() if btn_code == Qt.LeftButton: #如果是滑鼠左鍵按下 self.__dragPosition = mouseEvent.globalPos() - self.frameGeometry().topLeft() print(self.__dragPosition) mouseEvent.accept() elif btn_code == Qt.RightButton: print("It will close") self.close() #滑鼠右鍵關閉時鐘 def mouseMoveEvent(self, mouseEvent): #滑鼠移動事件 #在滑鼠拖動下,移動電子時鐘 self.move(mouseEvent.globalPos()-self.__dragPosition) mouseEvent.accept()
main.py
from PyQt5.QtWidgets import QApplication import sys from DigitalClock import DigitalClock def main(): app = QApplication(sys.argv) clock = DigitalClock(None) clock.show() sys.exit(app.exec_()) if __name__ == '__main__': main()