Skip to content

Instantly share code, notes, and snippets.

@mawillcockson
Last active March 13, 2021 16:10
Show Gist options
  • Select an option

  • Save mawillcockson/f869720e7596e2ffe107205835cae4e1 to your computer and use it in GitHub Desktop.

Select an option

Save mawillcockson/f869720e7596e2ffe107205835cae4e1 to your computer and use it in GitHub Desktop.
Extremely basic cli timer
"""
tells the time difference between input events
"""
import math
from datetime import datetime, timedelta
from typing import List
def now() -> datetime:
"returns a timezone-aware object for the time when it's called"
return datetime.now().astimezone()
def not_zero(num: float) -> bool:
"is num far enough away from zero"
if math.isclose(num, 0, abs_tol=1e-03):
# If it's close to zero
return False
return True
def plural(num: float) -> str:
"returns 's' if the number is not 1, otherwise nothing"
return "s" if num != 1 else ""
def format_diff(difference: timedelta) -> str:
"returns a prettified string representation of a timedelta"
minutes, seconds = divmod(difference.total_seconds(), 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
parts: List[str] = []
if days:
parts.append(f"{days:.0f} day{plural(days)}")
if hours:
parts.append(f"{hours:.4n} hour{plural(hours)}")
if minutes:
parts.append(f"{minutes:.4n} minute{plural(minutes)}")
if (not parts) or not_zero(seconds):
# Always add seconds if no other part will be displayed, and if there
# are parts already, only display seconds if it has something
parts.append(f"{seconds:.4n} seconds")
return ", ".join(parts)
if __name__ == "__main__":
while True:
input("Start?")
start = now()
input("Stop?")
print(format_diff(now() - start))
@mawillcockson
Copy link
Author

python -c "import urllib.request as r;exec(r.urlopen('https://gist.githubusercontent.com/mawillcockson/f869720e7596e2ffe107205835cae4e1/raw/timer.py').read().decode())"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment