Created
October 6, 2021 18:50
-
-
Save alexandru-dinu/c43efbd93b9dc1fd2141135359983211 to your computer and use it in GitHub Desktop.
Simple countdown until a deadline.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import math | |
import time | |
from datetime import datetime | |
from rich import box | |
from rich.align import Align | |
from rich.live import Live | |
from rich.panel import Panel | |
time_fmt = "%Y-%m-%d %H:%M:%S" | |
def gen(deadline: datetime) -> str: | |
now = datetime.now() | |
delta = (deadline - now).total_seconds() | |
if deadline < now: | |
return f"[bold] deadline has passed" | |
h, m = divmod(delta, 3600) | |
m, s = divmod(m, 60) | |
h, m, s = map(math.floor, [h, m, s]) | |
ht = "hour" + "s" * (h > 1 or h == 0) | |
mt = "minute" + "s" * (m > 1 or m == 0) | |
st = "second" + "s" * (s > 1 or s == 0) | |
return f"[bold]{h:2d} {ht}, {m:2d} {mt}, {s:2d} {st}" | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
"--deadline", | |
type=lambda d: datetime.strptime(d, time_fmt), | |
required=True, | |
help=f"Deadline in {time_fmt.replace('%', '%%')} format.", | |
) | |
parser.add_argument("--refresh_per_second", type=int, default=1) | |
args = parser.parse_args() | |
panel = lambda: Panel(Align.center(gen(args.deadline)), expand=True, box=box.SQUARE) | |
with Live(panel(), refresh_per_second=args.refresh_per_second) as live: | |
while True: | |
try: | |
time.sleep(0.5) | |
live.update(panel()) | |
except KeyboardInterrupt: | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment