Clock
Clock
A clock in Python typically involves displaying the current time and updating it periodically. The
core modules used for clock functionality include:
1. time module:
Contains functions to work with time.
Example: time.strftime() formats time, and time.sleep() pauses execution for a
specified duration.
2. strftime function:
%H : Displays hours in 24-hour format.
%M : Displays minutes.
%S : Displays seconds.
%p : Displays AM or PM.
3. sleep() function:
Pauses the program, allowing it to wait before performing the next action.
import time while True: # Get the current time current_time = time.strftime('%I:%M:%S
%p') # 12-hour format with AM/PM print(f"Current Time: {current_time}", end="\r") #
Overwrite the same line time.sleep(1) # Wait for 1 second
Step-by-Step Explanation:
1. time.strftime('%I:%M:%S %p') :
Formats the current time as Hours:Minutes:Seconds AM/PM in 12-hour format.
2. end="\r" :
Ensures the time is updated on the same line in the console.
3. time.sleep(1) :
Pauses for 1 second before refreshing the clock.
https://chatgpt.com/c/674866f5-9234-8001-8a96-458034abfb0a 1/2
11/28/24, 6:21 PM ChatGPT
Output:
When you run the script, you’ll see the time updating every second on the same line:
https://chatgpt.com/c/674866f5-9234-8001-8a96-458034abfb0a 2/2