Skip to content

Return a Duration from abs() and unary + on a Duration - #1098

Open
imsurya26 wants to merge 1 commit into
python-pendulum:masterfrom
imsurya26:fix/duration-abs
Open

imsurya26 wants to merge 1 commit into
python-pendulum:masterfrom
imsurya26:fix/duration-abs

Conversation

@imsurya26

Copy link
Copy Markdown

Pull Request Check List

  • Added tests for changed code.
  • Updated documentation for changed code (not needed).

Duration defines __neg__ but not __abs__ or __pos__, so abs() and unary + fall back to timedelta and return a plain datetime.timedelta. Years and months are folded into days and the Duration methods are lost:

>>> abs(pendulum.duration(years=-1, months=-2, days=-3))
datetime.timedelta(days=428)
>>> abs(pendulum.duration(hours=-5)).in_words()
AttributeError: 'datetime.timedelta' object has no attribute 'in_words'

This adds __pos__ (returns the duration itself) and __abs__ (returns -self when the total is negative, using the existing __neg__), so both now return a Duration with years and months kept. Interval keeps its own __abs__; +interval now returns the interval instead of a timedelta. As with timedelta, the sign of a mixed-sign duration is decided by total_seconds() (which uses the usual 365/30-day approximation for years and months).

Added test_abs and test_pos to tests/duration/test_arithmetic.py; both fail without the change. tests/duration and tests/interval pass, and ruff is clean.

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.

1 participant