I have the following index values in a pandas dataframe.
df.index[0:5]
DatetimeIndex(['2004-05-31', '2004-06-30', '2004-07-31', '2004-08-31',
'2004-09-30'],
dtype='datetime64[ns]', name='as_of_dt', freq=None)
How can I convert them into a list of like this:
['5/31/2004','6/30/2004','7/31/2004','8/31/2004']
To convert an index to a list in Pandas, use Index 's tolist() method.
Converting timestamp to datetime We may use the datetime module's fromtimestamp() method to convert the timestamp back to a datetime object. It returns the POSIX timestamp corresponding to the local date and time, as returned by time. time().
date attribute outputs an Index object containing the date values present in each of the entries of the DatetimeIndex object. Example #1: Use DatetimeIndex. date attribute to find the date part of the DatetimeIndex object.
You can use strftime
:
In [11]: df.index.strftime("%Y/%m/%d")
Out[11]:
array(['2004/05/31', '2004/06/30', '2004/07/31', '2004/08/31', '2004/09/30'],
dtype='<U10')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With