Skip to content

REF: simplify DTI._parse_string_to_bounds #31519

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 7 commits into from
Feb 5, 2020
Merged
Show file tree
Hide file tree
Changes from 5 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ Datetimelike
- Bug in :class:`Timestamp` where constructing :class:`Timestamp` from ambiguous epoch time and calling constructor again changed :meth:`Timestamp.value` property (:issue:`24329`)
- :meth:`DatetimeArray.searchsorted`, :meth:`TimedeltaArray.searchsorted`, :meth:`PeriodArray.searchsorted` not recognizing non-pandas scalars and incorrectly raising ``ValueError`` instead of ``TypeError`` (:issue:`30950`)
- Bug in :class:`Timestamp` where constructing :class:`Timestamp` with dateutil timezone less than 128 nanoseconds before daylight saving time switch from winter to summer would result in nonexistent time (:issue:`31043`)
- Bug in :meth:`Period.to_timestamp`, :meth:`Period.start_time` with microsecond frequency returning a timestamp one nanosecond earlier than the correct time (:issue:`31475`)

Timedelta
^^^^^^^^^
Expand Down
9 changes: 8 additions & 1 deletion pandas/_libs/tslibs/period.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ PyDateTime_IMPORT
from pandas._libs.tslibs.np_datetime cimport (
npy_datetimestruct, dtstruct_to_dt64, dt64_to_dtstruct,
pandas_datetime_to_datetimestruct, check_dts_bounds,
NPY_DATETIMEUNIT, NPY_FR_D)
NPY_DATETIMEUNIT, NPY_FR_D, NPY_FR_us)

cdef extern from "src/datetime/np_datetime.h":
int64_t npy_datetimestruct_to_datetime(NPY_DATETIMEUNIT fr,
Expand Down Expand Up @@ -1186,6 +1186,13 @@ cdef int64_t period_ordinal_to_dt64(int64_t ordinal, int freq) except? -1:
if ordinal == NPY_NAT:
return NPY_NAT

if freq == 11000:
# Microsecond, avoid get_date_info to prevent floating point errors
pandas_datetime_to_datetimestruct(ordinal, NPY_FR_us, &dts)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unrelated but have you ever thought about renaming this function to something like "int64ns_to_datetimestruct"? I always find myself thinking about what a "pandas_datetime" is

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i generally agree. i think it got this name because the numpy version is numpy_datetime_to_datetimestruct or something along those lines.

check_dts_bounds(&dts)
# Equivalent: return ordinal * 1000
return dtstruct_to_dt64(&dts)

get_date_info(ordinal, freq, &dts)
check_dts_bounds(&dts)
return dtstruct_to_dt64(&dts)
Expand Down
63 changes: 8 additions & 55 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,8 @@

import numpy as np

from pandas._libs import (
NaT,
Timedelta,
Timestamp,
index as libindex,
lib,
tslib as libts,
)
from pandas._libs.tslibs import ccalendar, fields, parsing, timezones
from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib as libts
from pandas._libs.tslibs import fields, parsing, timezones
from pandas.util._decorators import cache_readonly

from pandas.core.dtypes.common import _NS_DTYPE, is_float, is_integer, is_scalar
Expand Down Expand Up @@ -476,15 +469,14 @@ def _parsed_string_to_bounds(self, reso: str, parsed: datetime):

Parameters
----------
reso : Resolution
reso : str
Resolution provided by parsed string.
parsed : datetime
Datetime from parsed string.

Returns
-------
lower, upper: pd.Timestamp

"""
valid_resos = {
"year",
Expand All @@ -500,50 +492,11 @@ def _parsed_string_to_bounds(self, reso: str, parsed: datetime):
}
if reso not in valid_resos:
raise KeyError
if reso == "year":
start = Timestamp(parsed.year, 1, 1)
end = Timestamp(parsed.year + 1, 1, 1) - Timedelta(nanoseconds=1)
elif reso == "month":
d = ccalendar.get_days_in_month(parsed.year, parsed.month)
start = Timestamp(parsed.year, parsed.month, 1)
end = start + Timedelta(days=d, nanoseconds=-1)
elif reso == "quarter":
qe = (((parsed.month - 1) + 2) % 12) + 1 # two months ahead
d = ccalendar.get_days_in_month(parsed.year, qe) # at end of month
start = Timestamp(parsed.year, parsed.month, 1)
end = Timestamp(parsed.year, qe, 1) + Timedelta(days=d, nanoseconds=-1)
elif reso == "day":
start = Timestamp(parsed.year, parsed.month, parsed.day)
end = start + Timedelta(days=1, nanoseconds=-1)
elif reso == "hour":
start = Timestamp(parsed.year, parsed.month, parsed.day, parsed.hour)
end = start + Timedelta(hours=1, nanoseconds=-1)
elif reso == "minute":
start = Timestamp(
parsed.year, parsed.month, parsed.day, parsed.hour, parsed.minute
)
end = start + Timedelta(minutes=1, nanoseconds=-1)
elif reso == "second":
start = Timestamp(
parsed.year,
parsed.month,
parsed.day,
parsed.hour,
parsed.minute,
parsed.second,
)
end = start + Timedelta(seconds=1, nanoseconds=-1)
elif reso == "microsecond":
start = Timestamp(
parsed.year,
parsed.month,
parsed.day,
parsed.hour,
parsed.minute,
parsed.second,
parsed.microsecond,
)
end = start + Timedelta(microseconds=1, nanoseconds=-1)

grp = Resolution.get_freq_group(reso)
per = Period(parsed, freq=(grp, 1))
start, end = per.start_time, per.end_time

# GH 24076
# If an incoming date string contained a UTC offset, need to localize
# the parsed date to this offset first before aligning with the index's
Expand Down
19 changes: 18 additions & 1 deletion pandas/tests/scalar/period/test_asfreq.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pandas._libs.tslibs.frequencies import INVALID_FREQ_ERR_MSG, _period_code_map
from pandas.errors import OutOfBoundsDatetime

from pandas import Period, offsets
from pandas import Period, Timestamp, offsets


class TestFreqConversion:
Expand Down Expand Up @@ -656,6 +656,23 @@ def test_conv_secondly(self):

assert ival_S.asfreq("S") == ival_S

def test_conv_microsecond(self):
# GH#31475 Avoid floating point errors dropping the start_time to
# before the beginning of the Period
per = Period("2020-01-30 15:57:27.576166", freq="U")
assert per.ordinal == 1580399847576166

start = per.start_time
expected = Timestamp("2020-01-30 15:57:27.576166")
assert start == expected
assert start.value == per.ordinal * 1000

per2 = Period("2300-01-01", "us")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you split this off into a separate _raises test?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure

with pytest.raises(OutOfBoundsDatetime, match="2300-01-01"):
per2.start_time
with pytest.raises(OutOfBoundsDatetime, match="2300-01-01"):
per2.end_time

def test_asfreq_mult(self):
# normal freq to mult freq
p = Period(freq="A", year=2007)
Expand Down