Created
December 16, 2022 19:25
-
-
Save davidmankin/872388157e562dda8b90f631cc33657d to your computer and use it in GitHub Desktop.
Format a python timedelta (`time_delta`) as a compact string. Works for past and future.
This file contains hidden or 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
# Inspired by this stack overflow answer https://stackoverflow.com/a/17195550 by Bill Kidd | |
past = time_delta < datetime.timedelta(0) | |
if past: | |
hours, remainder = divmod(-1 * time_delta.total_seconds(), 3600) | |
minutes, seconds = divmod(remainder, 60) | |
else: | |
hours, remainder = divmod(time_delta.total_seconds(), 3600) | |
minutes, seconds = divmod(remainder, 60) | |
# Now format it compactly | |
hrs = f"{int(hours)}h " if hours else "" | |
min = f"{int(minutes)}m " if (not hours and minutes) or (hours == 1 and minutes != 0) else "" | |
sec = f"{int(seconds)}s " if not (hours or minutes) else "" | |
ago = "ago" if past else "" | |
in_s = "in " if not past else "" | |
print(f"{in_s}{hrs}{min}{sec}{ago}".strip()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some example results from my calendar…