Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: changing dataframe date index format

Would like to change the Date index of the dataframe from the default style into '%m/%d/%Y' format.

In: df
Out: 

  Date     Close     

2006-01-24  48.812471
2006-01-25  47.448712
2006-01-26  53.341202
2006-01-27  58.728122
2006-01-30  59.481986
2006-01-31  55.691974

df.index

 Out: 
 DatetimeIndex(['2006-01-04', '2006-01-05', '2006-01-06', '2006-01-09',
           '2006-01-10', '2006-01-11', '2006-01-12', '2006-01-13',
           '2006-01-17', '2006-01-18',
           ...
           '2018-02-21', '2018-02-22', '2018-02-23', '2018-02-26',
           '2018-02-27', '2018-02-28', '2018-03-01', '2018-03-02',
           '2018-03-05', '2018-03-06'],
          dtype='datetime64[ns]', name=u'Date', length=3063, freq=None)

Into:

In: df1
Out: 

 Date     Close     

01/24/2006  48.812471
01/25/2006  47.448712
01/26/2006  53.341202
01/27/2006  58.728122
01/28/2006  59.481986
01/29/2006  55.691974

I tried this method before...

 df1.index = pd.to_datetime(df.index, format = '%m/%d/%Y')
 df1.index = df.dt.strftime('%Y-%m-%d')

 AttributeError: 'DataFrame' object has no attribute 'dt'
like image 486
Maxi Avatar asked Mar 08 '18 08:03

Maxi


People also ask

How do I change the date format from YYYY MM DD in pandas?

Please notice that you can also specify the output date format other than the default one, by using the dt. strftime() method. For example, you can choose to display the output date as MM/DD/YYYY by specifying dt. strftime('%m/%d/%Y') .

How do I change the index of a DataFrame to a datetime?

To convert the index of a DataFrame to DatetimeIndex , use Pandas' to_datetime(~) method.

How do I change pandas datetime format?

Use astype() to Change datetime to String Format You can use this if the date is already in the format you want it in string form. The below example returns the date as a string with format %Y/%m/%d . dtype of column ConvertedDate will be object ( string ). Yields below output.

How do I change the date format in a DataFrame column in Python?

Function usedstrftime() can change the date format in python.


1 Answers

Use DatetimeIndex.strftime - instead dt need index:

df1.index = pd.to_datetime(df1.index, format = '%m/%d/%Y').strftime('%Y-%m-%d')

What is same:

df1.index = pd.to_datetime(df1.index, format = '%m/%d/%Y')
df1.index = df1.index.strftime('%Y-%m-%d')

EDIT if need convert DatetimeIndex to another string format:

print (df1.index)
DatetimeIndex(['2006-01-24', '2006-01-25', '2006-01-26', '2006-01-27',
               '2006-01-30', '2006-01-31'],
              dtype='datetime64[ns]', name='Date', freq=None)


df1.index = df1.index.strftime('%m/%d/%Y')
print (df1)
                Close
01/24/2006  48.812471
01/25/2006  47.448712
01/26/2006  53.341202
01/27/2006  58.728122
01/30/2006  59.481986
01/31/2006  55.691974
like image 117
jezrael Avatar answered Oct 02 '22 23:10

jezrael