Skip to content

Fix multi-digit decimal fractions in the pure Python duration parser - #1107

Open
farisbasha wants to merge 1 commit into
python-pendulum:masterfrom
farisbasha:fix/duration-multi-digit-fractions
Open

farisbasha wants to merge 1 commit into
python-pendulum:masterfrom
farisbasha:fix/duration-multi-digit-fractions

Conversation

@farisbasha

Copy link
Copy Markdown

Fixes #534

Pull Request Check List

  • Added tests for changed code.
  • Updated documentation for changed code.

Bug

The pure Python ISO 8601 duration parser (used when PENDULUM_EXTENSIONS=0 or the Rust extension is not available) turns the digits after the decimal mark into a fraction by dividing by 10, whatever the number of digits:

# PENDULUM_EXTENSIONS=0
pendulum.parse("PT1.25H")   # Duration(hours=3, minutes=30), expected 1h 15m
pendulum.parse("P1.05D")    # Duration(days=1, hours=12), expected 1d 1h 12m
pendulum.parse("PT16.48M")  # Duration(minutes=20, seconds=48), expected 16m 28.8s (#534)
pendulum.parse("P94.61625025224D")  # OverflowError: Python int too large to convert to C int

A fractional week also dropped everything below whole hours: P1.1W gave Duration(weeks=1, hours=16) instead of 1 week 16h 48m.

The Rust parser already returns the expected values for all of these.

Fix

Read the fraction as 0.<digits> (float(f"0.{digits}")) for weeks, days, hours and minutes, and pass the fractional days of a week duration on to Duration instead of truncating them to whole hours.

Tests

Added cases to test_parse_iso8601_duration (P1.1W, P1.25W, P1.25D, P1.05D, PT1.25H, PT16.48M). With PENDULUM_EXTENSIONS=0 all six fail on master and pass with the fix. With the Rust extension they pass before and after.

On the server, the full suite gives 1876 passed, 3 skipped in both modes. One test fails in both modes on master too (test_instance_with_aware_datetime_any_tzinfo), because of the machine's local time zone. ruff check, ruff format --check (0.14.11) and mypy on the changed file are clean.

This PR was prepared with AI assistance (Claude).

The pure Python ISO 8601 duration parser divided the digits after the
decimal mark by 10 whatever their count, so PT1.25H became 3h30m instead
of 1h15m and long fractions raised OverflowError. Fractional weeks also
dropped everything below whole hours. Parse the fraction as 0.<digits>,
which matches the Rust parser.

Fixes python-pendulum#534

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Incorrect duration parsing logic with decimals

1 participant