Time Expression Parser
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.
Warnings
- gotcha When parsing months ('mo') and years ('y'), `pytimeparse2` assumes fixed durations (30 days for a month, 365 days for a year). It does not account for leap years or leap seconds, which can lead to inaccuracies for precise date calculations.
- gotcha The `as_timedelta=True` option will return a `datetime.timedelta` object by default. If `python-dateutil` is installed, it will instead return a `dateutil.relativedelta.relativedelta` object, which offers more sophisticated handling for units like months and years. Ensure `python-dateutil` is installed if `relativedelta` behavior is expected.
- gotcha `pytimeparse2` is a fork of the original `pytimeparse` library. While functionally similar, using `from pytimeparse import parse` will import the older, less maintained version. Always use `from pytimeparse2 import parse` to ensure you are using this library.
Install
-
pip install pytimeparse2
Imports
- parse
from pytimeparse2 import parse
Quickstart
from pytimeparse2 import parse
# Parse to total seconds
seconds = parse('1 day, 2 hours, 30 minutes, 15 seconds')
print(f"Parsed to seconds: {seconds}")
# Parse to timedelta (requires python-dateutil for relativedelta if complex units are used)
timedelta_obj = parse('1y 2mo 3w 4d 5h 6m 7s 8ms', as_timedelta=True)
print(f"Parsed to timedelta: {timedelta_obj}")