Prefixdate
Prefixdate (version 0.5.0) is a Python library for parsing and processing date strings with varied levels of precision, such as '2001', '2001-4', or '2001-04-02'. It converts these partial dates into a structured format, enabling validation and re-formatting (e.g., normalizing '2001-4' to '2001-04'). The library is designed for handling ambiguous date prefixes and does not aim for full compliance with ISO 8601 or RFC 3339 standards, specifically excluding date ranges or calendar-week/day-of-year notations. It requires Python >=3.9. The latest version was released on August 4, 2025.
Warnings
- gotcha All `datetime` objects are converted to UTC and made naive (timezone information is stripped). Be aware of potential timezone issues if your application requires preserving original timezone data.
- gotcha The library explicitly does not support the full complexities of ISO 8601 and RFC 3339 standards, including date ranges and calendar-week/day-of-year notations.
- gotcha Invalid date strings (e.g., 'Boo!') or `None` passed to `parse()` will result in a `DatePrefix` object with `text` as `None` and `precision` as `Precision.EMPTY`.
- gotcha The library does not currently process milliseconds in date strings.
- gotcha The library does not validate for calendrically invalid dates (e.g., 'February 31st'). It focuses on string format parsing rather than date validity checks.
Install
-
pip install prefixdate
Imports
- parse
from prefixdate import parse
- normalize_date
from prefixdate import normalize_date
- Precision
from prefixdate import Precision
- parse_parts
from prefixdate import parse_parts
Quickstart
from prefixdate import parse, normalize_date, Precision, parse_parts
from datetime import datetime
# Parse returns a `DatePrefix` object:
date_obj_month = parse('2001-3')
assert date_obj_month.text == '2001-03'
assert date_obj_month.precision == Precision.MONTH
date_obj_year = parse(2001)
assert date_obj_year.text == '2001'
assert date_obj_year.precision == Precision.YEAR
# Handle invalid input which results in an empty DatePrefix
date_obj_invalid = parse('Not-a-date')
assert date_obj_invalid.text is None
assert date_obj_invalid.precision == Precision.EMPTY
# Normalize to a standard string:
assert normalize_date('2001-1') == '2001-01'
assert normalize_date('2001-00-00') == '2001'
# Normalize a datetime object with specific precision:
now_utc_iso = datetime.utcnow().isoformat()
minute_precision_date = normalize_date(now_utc_iso, precision=Precision.MINUTE)
# Example output for minute_precision_date: 'YYYY-MM-DDTHH:MM'
# Using parse_parts for structured input:
date_from_parts = parse_parts(2001, '3', None)
assert date_from_parts.precision == Precision.MONTH
assert date_from_parts.text == '2001-03'