Delta (Duration Parsing)
Delta is a Python library designed for human-friendly, context-aware parsing of duration strings. It allows users to convert natural language descriptions of time durations (e.g., '1 year 2 months and 3 days') into `datetime.timedelta` objects, optionally considering a specific start date for accurate calculations (e.g., for '2 months' relative to January vs. April). The library is currently at version 0.4.2 and appears to have a low release cadence.
Warnings
- gotcha The `delta` library appears to be minimally maintained, with the last notable activity on its GitHub repository around 2017. Users should be aware that it may not receive updates for new Python versions, bug fixes, or new features.
- gotcha When `delta.parse()` is called without an explicit `context` argument, it defaults to the current date. This means that calculations for relative units like '1 month' or '1 year' will vary depending on when the code is executed, leading to non-reproducible results. For example, '1 month' from January 31st is different from '1 month' from February 28th.
- gotcha The library's 'context-aware' parsing of durations for units like 'months' or 'years' relies on Python's `datetime` objects. However, the library does not explicitly handle timezone information in its parsing logic. If your applications involve timezone-aware `datetime` objects or cross daylight saving time boundaries, the calculations might produce unexpected results without careful management of the input `context` `datetime` objects.
- gotcha While designed for 'human-friendly' parsing, highly unusual, ambiguous, or malformed duration strings might lead to unexpected parsing results or unhandled exceptions. The robustness to a very wide variety of informal inputs is not extensively documented.
Install
-
pip install delta
Imports
- delta.parse
import delta from datetime import datetime duration = delta.parse('1 day')
Quickstart
import delta
from datetime import datetime
# Parse a duration without a specific context (defaults to current date)
duration_no_context = delta.parse('1 year 2 months and 3 days')
print(f"Duration without context: {duration_no_context}")
# Parse a duration with an explicit context date
context_date = datetime(2023, 1, 15) # January 15, 2023
duration_with_context = delta.parse('1 month and 2 weeks', context_date)
print(f"Duration with context {context_date.strftime('%Y-%m-%d')}: {duration_with_context}")
# Parse different string formats
duration_short_form = delta.parse('2y 3m 4w 5d')
print(f"Duration from short form: {duration_short_form}")