Skip to content

parse() rejects ISO 8601 week dates with years < 1000 (strptime %Y needs zero-padding) #1076

Description

@rahul05ranjan

Summary

pendulum.parse() rejects valid ISO 8601 week dates whose year is below 1000, even though the same years parse fine as ordinary calendar dates, and datetime.fromisoformat() accepts them:

>>> import pendulum
>>> pendulum.parse("2016-W34-6")
2016-08-27 00:00:00+00:00
>>> pendulum.parse("1000-W34-6")
1000-08-23 00:00:00+00:00
>>> pendulum.parse("0999-W34-6")
pendulum.parsing.exceptions.ParserError: Unable to parse string [0999-W34-6]
>>> pendulum.parse("0416-08-21")          # same year, calendar form: fine
0416-08-21 00:00:00+00:00
>>> pendulum.parse("0416-W34-6")
ParserError: Unable to parse string [0416-W34-6]
>>> pendulum.parse("0416W346")            # basic format: also broken
ParserError: Unable to parse string [0416W346]

All of 0999-W34-6, 0416-W34-6, 0416W346, 0416-W34, 0004-W10-5 raise ParserError while datetime.fromisoformat parses each of them.

Root cause

src/pendulum/parsing/iso8601.py, _get_iso_8601_week (lines ~448-452):

fmt = "%Y-%j"
string = f"{year}-{ordinal}"

dt = datetime.datetime.strptime(string, fmt)

The year is interpolated without zero-padding, so for year 416 the string is "416-240". strptime's %Y matches exactly four digits, so the lookup fails with ValueError: time data '416-240' does not match format '%Y-%j', which _parse then masks into the generic ParserError("Unable to parse string [...]").

The boundary is exact: years ≥ 1000 work, years ≤ 999 fail.

Expected behavior

Zero-pad the year (f"{year:04d}"), matching what the %Y directive requires. 0416-W34-6 then parses to 0416-08-27, same as datetime.fromisoformat.

Environment

  • pendulum 3.1.0 (current master, e06dace), Python 3.13, Linux.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions