Exercise
Continuous Date And Time
Objective
Develop a Python program that continuously displays the current date and time in real-time. The program should update the display every second and allow the user to stop it with a specific command or after a set period. Implement proper formatting for the date and time, and ensure that the program runs efficiently without excessive resource usage.
Example Python Exercise
Show Python Code
import time
from datetime import datetime
def display_current_time():
"""Function to display the current date and time every second."""
try:
while True:
# Get the current time and format it
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"Current Date and Time: {current_time}", end="\r") # Overwrite the line in the terminal
time.sleep(1) # Wait for 1 second before updating
except KeyboardInterrupt:
print("\nProgram stopped by user.")
except Exception as e:
print(f"An error occurred: {e}")
def main():
"""Main function to control the display of current time."""
# Ask the user if they want to start the real-time display
print("Press Ctrl+C to stop the program or let it run for a set period.")
# Start displaying the current time
display_current_time()
if __name__ == "__main__":
main()
Output
Press Ctrl+C to stop the program or let it run for a set period.
Current Date and Time: 2024-12-27 14:35:52
Current Date and Time: 2024-12-27 14:35:53
Current Date and Time: 2024-12-27 14:35:54
...
Share this Python Exercise