Skip to content

fix: precise_diff inconsistent with pendulum.DateTime subclasses (#906)#953

Open
r266-tech wants to merge 1 commit intopython-pendulum:masterfrom
r266-tech:fix/native-datetime-interval
Open

fix: precise_diff inconsistent with pendulum.DateTime subclasses (#906)#953
r266-tech wants to merge 1 commit intopython-pendulum:masterfrom
r266-tech:fix/native-datetime-interval

Conversation

@r266-tech
Copy link

Problem

When pendulum.interval() is called with native datetime.datetime objects, the resulting interval produces incorrect values for in_words(), hours, minutes, etc. This is because Interval.__init__ converts native datetimes to pendulum.DateTime, but the underlying Rust precise_diff function handles them inconsistently.

Example:

from datetime import datetime
import pendulum

start = datetime(2025, 7, 25, 19, 26, 34)
end = datetime(2025, 7, 29, 19, 26, 34)
interval = pendulum.interval(start, end)

# Before fix:
interval.in_words()   # "3 days 4 hours 33 minutes" (WRONG)
interval.hours        # 4 (WRONG)

# After fix:
interval.in_words()   # "4 days" (CORRECT)
interval.hours        # 0 (CORRECT)

Root Cause

In rust/src/python/helpers.rs, the precise_diff function uses inconsistent type checks:

  • Line 174: is_datetime: PyDateTime::is_type_of(dt1) — returns True for pendulum.DateTime (subclass)
  • Line 187: is_datetime: PyDateTime::is_exact_type_of(dt2) — returns False for pendulum.DateTime

When dt2.is_datetime is False, its hour/minute/second components are left at 0, producing an incorrect diff.

Fix

Changed line 187 from is_exact_type_of to is_type_of to match line 174.

Testing

  • Added regression test test_native_datetime_interval_consistency that verifies native and pendulum datetime inputs produce identical results
  • All 42 existing interval tests pass

Fixes #906

The  Rust helper used  for dt1
but  for dt2. Since
is a subclass of ,  returns False for it,
causing dt2's time components to be left at zero. This led to incorrect
interval calculations when using native  objects (which get
converted to  in ).

Fixes python-pendulum#906
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.

Pendulum interval seems incompatible with Python native datetime

2 participants