Convert datetime column to row columns? Pandas - Python

I am trying to convert a datetime column to a string in a Pandas dataframe.

The syntax I have so far is:

all_data['Order Day new'] = dt.date.strftime(all_data['Order Day new'], '%d/%m/%Y')

but this returns an error:

descriptor 'strftime' requires an object 'datetime.date', but received a 'Series'.

Can someone tell me where I am going wrong.

+8
source share
1 answer

If you are using a version 0.17.0or higher, you can call this using which is vectorized: .dt.strftime

all_data['Order Day new'] = all_data['Order Day new'].dt.strftime('%Y-%m-%d')

** If your version of pandas is older than 0.17.0you need to call applyand transfer data to strftime:

In [111]:

all_data = pd.DataFrame({'Order Day new':[dt.datetime(2014,5,9), dt.datetime(2012,6,19)]})
print(all_data)
all_data.info()
  Order Day new
0    2014-05-09
1    2012-06-19
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 1 columns):
Order Day new    2 non-null datetime64[ns]
dtypes: datetime64[ns](1)
memory usage: 32.0 bytes

In [108]:

all_data['Order Day new'] = all_data['Order Day new'].apply(lambda x: dt.datetime.strftime(x, '%Y-%m-%d'))
all_data
Out[108]:
  Order Day new
0    2014-05-09
1    2012-06-19
In [109]:

all_data.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 1 columns):
Order Day new    2 non-null object
dtypes: object(1)
memory usage: 32.0+ bytes

strftime , Series , ,

+14

All Articles