Convert explicit duration strings into exact milliseconds
Python
Parse configuration durations without binary floating-point rounding.
Parse configuration durations without binary floating-point rounding. This stdin-based Python CLI processes one bounded JSON request and returns the documented JSON result. It does not execute jobs or contact external services. Inspect its limits before adapting it to an application.
Before you start
Python 3.12 standard library; no third-party packages. Verified with the recorded pinned runtime.
One UTF-8 JSON object on stdin, no command-line arguments. Maximum encoded request size is 20000 bytes.
Build and check
Save the source as convert-duration-to-milliseconds-python.py.
Save the example JSON below as request.json.
Run python3 convert-duration-to-milliseconds-python.py < request.json.
Compare the parsed JSON result with the expected output. Invalid input exits 2 with empty stdout and a generic stderr message.
Limits to understand
Input is limited to 20000 bytes and exactly one duration field.
Durations must use the specified ASCII grammar and resolve to an integer number of milliseconds between 0 and 86400000 inclusive.
The program only converts durations; it does not sleep or impose timeouts.
Input exactly {"duration":string}. Grammar: 0 or a nonzero ASCII digit followed by up to 8 ASCII digits, optionally a dot and 1..3 ASCII digits, then ms, s, m or h. No whitespace, signs, exponent or leading zeros.
Use exact decimal arithmetic. Convert with ms=1,s=1000,m=60000,h=3600000. Result must be an integer in 0..86400000; reject fractional milliseconds and larger results.
Output {"milliseconds":integer}. This does not sleep or impose timeouts.
The complete encoded input is limited to 20000 bytes; one additional byte can be read to detect overflow.
This is a bounded local helper. Passing the recorded cases does not verify every input, every Python version or an external integration.
This browser preview builds code locally. It does not contact an API or run the code.
Default example ready.
Python example
import json
import re
import sys
_PATTERN = re.compile(r'(0|[1-9][0-9]{0,8})(?:\.([0-9]{1,3}))?(ms|s|m|h)')
_FACTORS = {'ms': 1, 's': 1000, 'm': 60000, 'h': 3600000}
def reject_number(_text):
# No JSON number is permitted by this input schema.
raise ValueError('invalid input')
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError('invalid input')
result[key] = value
return result
def main():
try:
if len(sys.argv) != 1:
raise ValueError('invalid input')
raw = sys.stdin.buffer.read(20001)
if len(raw) > 20000:
raise ValueError('invalid input')
text = raw.decode('utf-8', errors='strict')
# Escaped surrogates are also excluded by the exact schema and grammar.
if any(0xD800 <= ord(char) <= 0xDFFF for char in text):
raise ValueError('invalid input')
data = json.loads(
text,
object_pairs_hook=unique_object,
parse_int=reject_number,
parse_float=reject_number,
parse_constant=reject_number,
)
if not isinstance(data, dict) or set(data) != {'duration'}:
raise ValueError('invalid input')
duration = data['duration']
if not isinstance(duration, str):
raise ValueError('invalid input')
match = _PATTERN.fullmatch(duration)
if match is None:
raise ValueError('invalid input')
whole, fraction, unit = match.groups()
# Exact fixed-point decimal arithmetic, with three decimal places.
thousandths = int(whole) * 1000 + int((fraction or '').ljust(3, '0'))
milliseconds, remainder = divmod(thousandths * _FACTORS[unit], 1000)
if remainder or not 0 <= milliseconds <= 86400000:
raise ValueError('invalid input')
except (ValueError, UnicodeError, RecursionError, OverflowError):
sys.stderr.write('Invalid input\n')
return 2
sys.stdout.write(json.dumps({'milliseconds': milliseconds}, separators=(',', ':')) + '\n')
return 0
if __name__ == '__main__':
sys.exit(main())
What to verify after running
Run the documented example and compare the JSON result.
Confirm malformed requests exit 2 without copying input data into diagnostic messages.
30 independent CLI cases passed on this exact source, including an unexpected-argument check.
Request or format preview
Illustrative preview. No provider response, price or balance is fetched.
Code license: MIT. Keep the license notice with your copy.
Example version 1.0.0 · Documentation reviewed 2026-11-15.
30 recorded CLI cases passed in rootless Docker on the pinned Python 3.12 runtime, with 512 MiB RAM, 1 CPU, no network, and read-only source. Other runtimes and all possible inputs are not verified.