Below is a simple Python script that prints the current time live, updating every second. We'll use the time and datetime modules for this purpose.
import time
from datetime import datetime
def print_live_time():
"""
Prints the current time live, updating every second.
"""
try:
while True:
# Get current time
current_time = datetime.now().strftime("%H:%M:%S")
# Print current time, overwrite previous output
print(f"\rCurrent Time: {current_time}", end='')
# Wait for 1 second before updating time again
time.sleep(1)
except KeyboardInterrupt:
print("\nStopped live time updates.")
if __name__ == "__main__":
print("Press Ctrl+C to stop...")
print_live_time()
How It Works:
Infinite Loop: The while True loop runs indefinitely until manually stopped.
Get Current Time: datetime.now().strftime("%H:%M:%S") fetches the current system time and formats it into hours, minutes, and seconds (%H:%M:%S).
%H - 24-hour clock (00 to 23)
%M - Minute (00 to 59)
%S - Second (00 to 59)
Live Update: \r in the print statement returns the cursor to the beginning of the line, allowing each new time to overwrite the previous one, creating a live update effect. end='' prevents print from appending a newline character.
Delay: time.sleep(1) pauses execution for 1 second between each time update.
Exit on Ctrl+C: The try-except block catches KeyboardInterrupt (raised when you press Ctrl+C), stopping the loop cleanly and printing a farewell message.
Running the Code:
Save this code in a .py file, for example, live_time.py.
Open a terminal or command prompt.
Navigate to the directory where live_time.py is saved.
Run the script using Python: python live_time.py
You'll see the live time updating. Press Ctrl+C to stop.
Tips:
For a 12-hour clock format, replace "%H:%M:%S" with "%I:%M:%S %p" (%I for 12-hour clock and %p for AM/PM).
To include the date, modify the format string, e.g., "%Y-%m-%d %H:%M:%S".
Experiment with different time.sleep() values for faster or slower updates.
Enjoy your live ticking clock!
write python code to print time live · The Chat Archive