Digital Clock
BasicBuild a real-time clock that updates every second
1) Project Overview
We will build a simple digital clock that shows the current date and time and updates every second. It will run in the terminal (the black/white text window). You will see the time change just like a real digital clock.
2) Learning Objectives
By the end of this project, you will:
- Use Python's time module to get the current date and time.
- Format time into a friendly string like HH:MM:SS.
- Use a while loop to repeat actions every second.
- Pause a program with
time.sleep(). - Print neatly on one line using carriage return (\r) and flush.
- Handle stopping the program safely with Ctrl+C.
3) Step-by-Step Explanation
- Create a new file:
- Open your code editor and create a file named
digital_clock.py.
- Open your code editor and create a file named
- Import the time module:
- We will use
time.strftime()to format the time andtime.sleep()to wait 1 second between updates.
- We will use
- Decide the display:
- We'll show the date (like Mon, 14 Oct 2025) and the time (like 19:05:21) on one line.
- Make an infinite loop:
- A
while Trueloop lets the clock update forever (until you stop it).
- A
- Format the current time:
- Use
time.strftime("%H:%M:%S")for 24-hour time (e.g., 19:05:21). - Optional: use
"%I:%M:%S %p"for 12-hour time (e.g., 07:05:21 PM). - For the date, use something like
"%a, %d %b %Y"(e.g., Mon, 14 Oct 2025).
- Use
- Print on one line:
- Use
print("\r" + line, end="", flush=True)so the time updates on the same line. - Note: In some editors like IDLE, this may still print on new lines. That's okay. Try running the file in your system terminal for the "one-line" effect.
- Use
- Pause for one second:
- Use
time.sleep(1)so the time updates once per second.
- Use
- Allow a clean exit:
- Wrap the loop in try/except and catch KeyboardInterrupt so pressing Ctrl+C stops the clock nicely.
- Run your program:
- Open a terminal/command prompt, go to the folder with your file, and run:
python digital_clock.py
- Open a terminal/command prompt, go to the folder with your file, and run:
4) Complete and Well-Commented Python Code
# digital_clock.py
# A simple digital clock that updates every second in the terminal.
import time # Built-in module for working with time and dates
def main():
print("Digital Clock - Press Ctrl+C to stop")
try:
while True:
# Format the current date and time.
# Example date: Mon, 14 Oct 2025
date_part = time.strftime("%a, %d %b %Y")
# Example time (24-hour): 19:05:21
# For 12-hour time with AM/PM, you could use: "%I:%M:%S %p"
time_part = time.strftime("%H:%M:%S")
# Build the display line
line = f"{date_part} {time_part}"
# Print on the same line:
# \r moves the cursor to the start of the line.
# end="" avoids adding a new line each time.
# flush=True forces the text to show immediately.
print("\r" + line, end="", flush=True)
# Wait 1 second before updating again
time.sleep(1)
except KeyboardInterrupt:
# If the user presses Ctrl+C, exit nicely.
print("\nClock stopped. Goodbye!")
# Run the program only if this file is executed directly
if __name__ == "__main__":
main()
5) Output Examples
When you run the program, you'll see something like:
Mon, 14 Oct 2025 19:05:21
Mon, 14 Oct 2025 19:05:22
Mon, 14 Oct 2025 19:05:23
... (updates every second)
If you run it in a system terminal, you may see the time update on a single line, like this:
Mon, 14 Oct 2025 19:05:23 [and the seconds keep changing in place]
Press Ctrl+C to stop:
6) Small Exercise (Try This!)
Add a friendly greeting based on the hour
Idea: Show "Good Morning", "Good Afternoon", or "Good Evening" before the time.
Hints:
- Get the current hour as a number:
hour = int(time.strftime("%H")) - Use if/elif/else:
- 5 <= hour < 12: "Good Morning"
- 12 <= hour < 18: "Good Afternoon"
- else: "Good Evening"
- Include the greeting in your line:
line = f"{greeting} | {date_part} {time_part}"
7) Summary
Great job! You built a working digital clock using just a few lines of Python. You learned how to loop forever, pause your program, format dates and times, and print smoothly. Small projects like this build strong foundations. Keep experimenting—tiny changes can lead to cool new features. You've got this!