Skip to content

Instantly share code, notes, and snippets.

@codeinthehole
Created September 28, 2023 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeinthehole/e2ab6cde6a5d4d133afd224b7226068a to your computer and use it in GitHub Desktop.
Save codeinthehole/e2ab6cde6a5d4d133afd224b7226068a to your computer and use it in GitHub Desktop.
Alfred workflow script for converting numbers to durations
#!/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]))
@codeinthehole
Copy link
Author

Workflow set-up looks like this:

image

where the script filter looks like this:

image

Looks like this in action:

image

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