pytimeparse2 is a small Python library for parsing various human-readable time expressions (e.g., '2h32m', '1.5 days', '5hr 34mins 56secs') into a total number of seconds or `datetime.timedelta` objects. It is a fork of the original `pytimeparse` project, aiming for optimized functionality and stable support. The current version is 1.7.1, and releases are made on an as-needed basis for bug fixes and feature enhancements.
pip install pytimeparse2Verified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to parse a time expression into total seconds or a `datetime.timedelta` object using the `parse` function. For advanced `timedelta` results (e.g., handling months/years), `python-dateutil` is recommended.
Be aware of this limitation when parsing expressions involving 'mo' or 'y'. For highly accurate date/time arithmetic across varying year lengths, consider using libraries like `python-dateutil` directly, especially its `relativedelta` functionality.
Install `python-dateutil` via `pip install python-dateutil` if `relativedelta` objects are desired for more precise and flexible date calculations with `as_timedelta=True`.
Explicitly import from `pytimeparse2` (i.e., `from pytimeparse2 import parse`) to leverage the updates and support provided by this specific fork.
Change the import statement to use `pytimeparse2` instead: `from pytimeparse2 import parse`.
Provide a valid time string that `pytimeparse2` can parse, or catch the `ParseError` exception to handle gracefully if invalid input is expected: `try: parse('invalid', error=True) except ParseError: print('Invalid time string')`.The main parsing function `parse` is directly available from the `pytimeparse2` module; use `from pytimeparse2 import parse` and then call `parse('time string')` directly.Ensure the argument passed to `parse` is always a string: `parse('123')` instead of `parse(123)`.