Milhouse
Milhouse

Reputation: 595

Datetime issues

I'm trying to get a datetime series in a certain format and dtype. Below is the series and the output.

enr = pd.date_range('4/1/2013', '7/1/2013', freq="M")

print(enr)

DatetimeIndex(['2013-04-30', '2013-05-31', '2013-06-30', '2013-07-31'], dtype='datetime64[ns]', freq='M')

I'd like for the final output to look like the table below and be in a datetime format.

Date      Date    
4/1/2013 2013-04
5/1/2013 2013-05
6/1/2013 2013-06
7/1/2013 2013-07

Below is the code I am using but am getting the error message below that:

enr['Date'] = pd.to_datetime(enr).dt.to_period('M')

print(enr)

AttributeError: 'DatetimeIndex' object has no attribute 'dt'

Upvotes: 1

Views: 399

Answers (1)

Alexander
Alexander

Reputation: 109520

Here are some examples of time manipulations.

enr = pd.date_range('4/1/2013', '7/1/2013', freq="M")

df = pd.DataFrame(
    {'period': [d.to_period('M') for d in enr], 
     'str_month': [d.strftime('%Y-%m') for d in enr], 
     'datetime': [d.to_pydatetime() for d in enr]}
    , index=enr)

>>> df
             datetime  period str_month
2013-04-30 2013-04-30 2013-04   2013-04
2013-05-31 2013-05-31 2013-05   2013-05
2013-06-30 2013-06-30 2013-06   2013-06

>>> {col: type(df.ix[0, col]) for col in df}
{'datetime': pandas.tslib.Timestamp,
 'period': pandas._period.Period,
 'str_month': str}

Upvotes: 1

Related Questions