Created
September 28, 2023 10:28
-
-
Save codeinthehole/e2ab6cde6a5d4d133afd224b7226068a to your computer and use it in GitHub Desktop.
Alfred workflow script for converting numbers to durations
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
#!/usr/bin/python3 | |
# | |
# This script can be used as a Alfred Script Filter in a custom workflow for converting numbers to durations. | |
# To do so, create a new workflow, add a script filter with contents './convert "$@"', ensuring that the | |
# query is passed as "with input as argv". | |
# | |
# It's useful to connect a "Copy to Clipboard" output action to make it easier to paste the duration string somewhere. | |
import argparse | |
import json | |
import sys | |
def main(query: str) -> dict: | |
""" | |
Main entry point for the script. | |
""" | |
# Parse query. | |
try: | |
duration = num_to_duration(int(query)) | |
except ValueError: | |
duration = "..." | |
valid = False | |
subtitle = "Enter a valid number of seconds" | |
else: | |
valid = True | |
subtitle = "Hit enter to copy to clipboard" | |
# See https://www.alfredapp.com/help/workflows/inputs/script-filter/json/ | |
payload = { | |
"items": [ | |
{ | |
"uid": "duration", | |
"title": duration, | |
"subtitle": subtitle, | |
"arg": duration, # This is passed to the output action. | |
"valid": valid, | |
} | |
] | |
} | |
return json.dumps(payload) | |
def num_to_duration(seconds: int) -> str: | |
""" | |
Convert a integer number of seconds to a duration string. | |
""" | |
hours, remainder = divmod(seconds, 3600) | |
minutes, seconds = divmod(remainder, 60) | |
return f"{hours:02.0f}:{minutes:02.0f}:{seconds:02.0f}" | |
if __name__ == "__main__": | |
if len(sys.argv) >= 2: | |
print(main(sys.argv[1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Workflow set-up looks like this:
where the script filter looks like this:
Looks like this in action: