JAG2024
JAG2024

Reputation: 4317

Return specific dates, months from any year using python date time

To clarify, I actually need to return multiple months, for example October through December.

I have a dataframe with 10000s of rows where my index is a time_stamp. I want to get the values that fall between certain months for all of the years in the dataframe.

I've tried this: print(df.loc['%Y-10-01':'%Y-12-31']) along with YYYY, ****, %y but I can't figure out how to return the date time objects that match for any year.

The dataframe df looks something like this:

2015-07-13  0.000000    0.000000    0.000000    0.000000    0.000000    0.000000    0.000000    17.018001   0.000000    0.000000    0.000000
2017-07-27  0.000000    1.016000    0.000000    0.000000    0.000000    0.000000    0.000000    0.000000    0.000000    0.000000    0.000000
2017-07-03  1.778000    12.700000   3.048000    7.874000    5.588000    2.540000    28.448001   26.670000   58.420003   19.812001   12.446000

Upvotes: 1

Views: 346

Answers (1)

cs95
cs95

Reputation: 402333

For your particular problem, it would seem like an isin check on a range of months would be the simplest:

df.iloc[df.index.month.isin(np.r_[10:13])]

np.r_ makes it convenient to specify intermittent ranges. For example, if you want Jan-Feb, April, and Oct-Dec, use:

i = np.r_[1:3, 4, 10:13]

i
array([ 1,  2,  4, 10, 11, 12])

Upvotes: 1

Related Questions