Digital Clock
This program displays a digital clock with the current time. Rather than render numeric characters directly, the sevseg.py module from Project 64, “Seven-Segment Display Module,” generates the drawings for each digit. This program is similar to Project 14, “Countdown.”
digital_clock.py
1"""Digital Clock, by Al Sweigart al@inventwithpython.com
2Displays a digital clock of the current time with a seven-segment
3display. Press Ctrl-C to stop.
4More info at https://en.wikipedia.org/wiki/Seven-segment_display
5Requires sevseg.py to be in the same folder.
6This code is available at https://nostarch.com/big-book-small-python-programming
7Tags: tiny, artistic"""
8
9import sys, time
10import sevseg # Imports our sevseg.py program.
11
12try:
13 while True: # Main program loop.
14 # Clear the screen by printing several newlines:
15 print('\n' * 60)
16
17 # Get the current time from the computer's clock:
18 currentTime = time.localtime()
19 # % 12 so we use a 12-hour clock, not 24:
20 hours = str(currentTime.tm_hour % 12)
21 if hours == '0':
22 hours = '12' # 12-hour clocks show 12:00, not 00:00.
23 minutes = str(currentTime.tm_min)
24 seconds = str(currentTime.tm_sec)
25
26 # Get the digit strings from the sevseg module:
27 hDigits = sevseg.getSevSegStr(hours, 2)
28 hTopRow, hMiddleRow, hBottomRow = hDigits.splitlines()
29
30 mDigits = sevseg.getSevSegStr(minutes, 2)
31 mTopRow, mMiddleRow, mBottomRow = mDigits.splitlines()
32
33 sDigits = sevseg.getSevSegStr(seconds, 2)
34 sTopRow, sMiddleRow, sBottomRow = sDigits.splitlines()
35
36 # Display the digits:
37 print(hTopRow + ' ' + mTopRow + ' ' + sTopRow)
38 print(hMiddleRow + ' * ' + mMiddleRow + ' * ' + sMiddleRow)
39 print(hBottomRow + ' * ' + mBottomRow + ' * ' + sBottomRow)
40 print()
41 print('Press Ctrl-C to quit.')
42
43 # Keep looping until the second changes:
44 while True:
45 time.sleep(0.01)
46 if time.localtime().tm_sec != currentTime.tm_sec:
47 break
48except KeyboardInterrupt:
49 print('Digital Clock, by Al Sweigart al@inventwithpython.com')
50 sys.exit() # When Ctrl-C is pressed, end the program.