REGEXVAULTv2.0
Localization/Date Formats
Verified Safe

ISO 8601 Duration Regex for Python

/^P(?!$)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?!$)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching iso 8601 duration, ported and verified for Python. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.

Python Implementation

Python
# ISO 8601 Duration
# ReDoS-safe | RegexVault — Localization > Date Formats

import re

iso_8601_duration_pattern = re.compile(r'^P(?!$)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?!$)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$')

def validate_iso_8601_duration(value: str) -> bool:
    return bool(iso_8601_duration_pattern.fullmatch(value))

# Example
print(validate_iso_8601_duration("P1Y"))  # True

Test Cases

Matches (Valid)
Rejects (Invalid)
P1YP
P1Y2M3DPT
PT1H30M1Y
P1Y2M3DT4H5M6SP1YT
P30DP1Y2M3DT
PT0.5S
P1W

When to use this pattern

This pattern is drawn from the Localization > Date Formats category and carries a ReDoS-safe certification. That matters for Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.

Common Pitfalls

ISO 8601 specifies that W (weeks) cannot be combined with Y, M, or D components. This pattern allows the combination — enforce the restriction at application level if strict compliance is required.

Technical Notes

Lookahead (?!$) ensures at least one component is present. Capture groups: 1=years, 2=months, 3=weeks, 4=days, 5=hours, 6=minutes, 7=seconds. Weeks (W) cannot be combined with other date components in strict ISO 8601.

Have a pattern that belongs in the vault?

Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.

Submit a Pattern