Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas generate date range of Beginning Month

Tags:

python

pandas

What is going on here? I need to generate a dataframe with beginning of month dates,,(1-1-2014 To 12-1-2014) fwiw I use the fcast_year variable elsewhere where I need the end of month, hence doing date math

from pandas.tseries.offsets import *
fcast_yr=pd.to_datetime('2014-12-31')
x=(fcast_yr + pd.DateOffset(days= -30)) # to set x to 2014-12-01
d=pd.date_range((x +pd.DateOffset(months=-10)), periods=12, freq='MS') #"MS" means start of month!!
print d.values

Gives these end of month values....yech!!

['2014-01-31T18:00:00.000000000-0600' '2014-02-28T18:00:00.000000000-0600'
 '2014-03-31T19:00:00.000000000-0500' '2014-04-30T19:00:00.000000000-0500'
 '2014-05-31T19:00:00.000000000-0500' '2014-06-30T19:00:00.000000000-0500'
 '2014-07-31T19:00:00.000000000-0500' '2014-08-31T19:00:00.000000000-0500'
 '2014-09-30T19:00:00.000000000-0500' '2014-10-31T19:00:00.000000000-0500'
 '2014-11-30T18:00:00.000000000-0600' '2014-12-31T18:00:00.000000000-0600']

Using 13.0 pf Pandas

like image 918
dartdog Avatar asked Jan 29 '14 01:01

dartdog


1 Answers

You don't need to coerce the timestamp to the begin month; the frequency will do it (but your answer is correct).

The 'values' are just the way numpy represents dates (they are UTC).

In [8]: pd.date_range((Timestamp('20141231') +pd.DateOffset(months=-11)), periods=12, freq='MS')
Out[8]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-02-01, ..., 2015-01-01]
Length: 12, Freq: MS, Timezone: None
like image 77
Jeff Avatar answered Oct 12 '22 11:10

Jeff