Time Expression Parser

1.7.1 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

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.

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}")

view raw JSON →