Objectivo
Desarrollar un programa Python que muestre continuamente la fecha y la hora actuales en tiempo real. El programa debería actualizar la pantalla cada segundo y permitir al usuario detenerla con un comando específico o después de un período determinado. Implementar un formato adecuado para la fecha y la hora, y garantizar que el programa se ejecute de manera eficiente sin un uso excesivo de recursos.
Ejemplo Ejercicio Python
Mostrar Código Python
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
...
Código de Ejemplo copiado
Comparte este ejercicios Python