Skip to content

BUG: Negative freq in date_range produces values out of start and endpoints #56832

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2790,7 +2790,12 @@ def _generate_range(
if start and not offset.is_on_offset(start):
# Incompatible types in assignment (expression has type "datetime",
# variable has type "Optional[Timestamp]")
start = offset.rollforward(start) # type: ignore[assignment]

# GH #56147 account for negative direction and range bounds
if offset.n >= 0:
start = offset.rollforward(start) # type: ignore[assignment]
else:
start = offset.rollback(start) # type: ignore[assignment]

# Unsupported operand types for < ("Timestamp" and "None")
if periods is None and end < start and offset.n >= 0: # type: ignore[operator]
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/indexes/datetimes/test_date_range.py
Original file line number Diff line number Diff line change
Expand Up @@ -1729,3 +1729,18 @@ def test_date_range_partial_day_year_end(self, unit):
freq="YE",
)
tm.assert_index_equal(rng, exp)

def test_date_range_negative_freq_year_end_inbounds(self, unit):
# GH#56147
rng = date_range(
start="2023-10-31 00:00:00",
end="2021-10-31 00:00:00",
freq="-1YE",
unit=unit,
)
exp = DatetimeIndex(
["2022-12-31 00:00:00", "2021-12-31 00:00:00"],
dtype=f"M8[{unit}]",
freq="-1YE",
)
tm.assert_index_equal(rng, exp)