RFC 3339 Date/Time Formatting
The `rfc3339` library for Python provides utilities to format `datetime` objects into RFC 3339 compliant strings and to parse such strings back into `datetime` objects. It closely adheres to the RFC 3339 standard, including providing its own UTC `tzinfo` implementation. While the PyPI package `6.2` was last released in 2019, the primary GitHub repository shows recent maintenance activity, indicating it's still actively maintained, albeit with a slow release cadence.
Warnings
- gotcha The `rfc3339` library, like Python's standard `datetime` module, does not support or account for leap seconds in its parsing or generation. While RFC 3339 specifies them, this library (and Python's native `datetime`) treats all minutes as 60 seconds long.
- gotcha The library explicitly states it does not implement RFC 3339 Section 4.3, "Unknown Local Offset Convention." This means it might not correctly handle or generate timestamps where the local offset is truly unknown and represented by '-00:00' semantically distinct from '+00:00' or 'Z'.
- gotcha The parsing routines in `rfc3339` primarily focus on Section 5.6, "Internet Date/Time Format." While this is a common and strict profile of RFC 3339 (and ISO 8601), more lenient or alternative RFC 3339 compliant variations might not be parsed correctly. For broader ISO 8601 parsing, other libraries like `python-dateutil` might be more suitable.
- gotcha Python's `datetime` module itself has complexities with timezones, especially when dealing with naive datetimes or converting between different timezone representations (local vs. UTC, DST transitions). While `rfc3339` provides its own UTC `tzinfo`, inconsistencies can arise if not carefully managed with the underlying `datetime` objects.
Install
-
pip install rfc3339
Imports
- rfc3339
import rfc3339
Quickstart
from datetime import datetime, timezone
import rfc3339
# Get current UTC time
now_utc = datetime.now(timezone.utc)
# Format a datetime object to RFC 3339 string
rfc3339_string = rfc3339.rfc3339(now_utc)
print(f"Formatted: {rfc3339_string}")
# Parse an RFC 3339 string back to a datetime object
parsed_datetime = rfc3339.parse_rfc3339(rfc3339_string)
print(f"Parsed: {parsed_datetime}")
# Example with a specific date and offset
date_with_offset_str = "2023-10-27T10:00:00-05:00"
parsed_with_offset = rfc3339.parse_rfc3339(date_with_offset_str)
print(f"Parsed with offset: {parsed_with_offset}")