Build a Live Countdown Timer for Events in Python
A Python script that displays a real-time countdown to a target date and time, updating every second in the console.
Python code
21 linesimport datetime
import time
def countdown(event_name, target_datetime):
"""Displays a live countdown to a target datetime."""
while True:
now = datetime.datetime.now()
remaining = target_datetime - now
if remaining.total_seconds() <= 0:
print(f"\n🚀 {event_name} is happening NOW!")
break
days = remaining.days
hours, remainder = divmod(remaining.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
print(f"\r⏳ {event_name} in {days}d {hours:02d}:{minutes:02d}:{seconds:02d}", end="", flush=True)
time.sleep(1)
if __name__ == "__main__":
# Example: Countdown to New Year 2026
target = datetime.datetime(2026, 1, 1, 0, 0, 0)
countdown("New Year 2026", target)
Output
⏳ New Year 2026 in 365d 00:00:00
⏳ New Year 2026 in 365d 23:59:59
... (updates every second)
🚀 New Year 2026 is happening NOW!
How it works
The countdown uses datetime.datetime.now() to get the current time and subtracts the target time to compute the remaining duration. The while True loop keeps the countdown running until the event occurs. divmod splits the remaining seconds into hours, minutes, and seconds for a clean display. The \r carriage return overwrites the same line in the terminal, and flush=True ensures immediate output. When the remaining time reaches zero or below, the loop breaks and prints a launch message.
Common mistakes
- Using `datetime.datetime` instead of `datetime.datetime.now()` for the current time.
- Forgetting to handle timezone-aware datetimes when mixing naive and aware objects.
- Not accounting for the possibility of the target being in the past (check `remaining.total_seconds() <= 0`).
- Using `print` without `end=""` or `flush=True`, causing each update on a new line or buffered output.
Variations
- Use `threading.Timer` to schedule a one-time callback instead of a busy loop.
- Add a `timezone` argument using `pytz` or `zoneinfo` for timezone-aware countdowns.
Real-world use cases
- Running a live countdown on a digital signage display before a product launch event.
- Triggering automated deployment scripts exactly at a scheduled release window.
- Embedding a countdown in a CLI tool to remind users of pending deadline or maintenance.
Sponsored
More from Automation & scripting
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
Keep learning
Related tutorials and quizzes for this topic.