strip time using strftime in pandas column as series object

59 views Asked by At

I have a pandas dataframe containing time in column 1 and field x, y and z in other columns of the form

df = 0 1 2 3 0 2010-Feb-13/08:44:15.588 -2.524 0.071 -0.606 1 2010-Feb-13/08:44:15.588 -2.539 0.079 -0.523 2 2010-Feb-13/08:44:15.588 -2.526 0.064 -0.523 3 2010-Feb-13/08:44:15.588 -2.536 0.069 -0.496 4 2010-Feb-13/08:44:15.588 -2.539 0.079 -0.551

I want to convert to datetime the column corresponding to 0 and subsequently convert it to a numpy array of datetime containing time stripped to '%H:%M:%s'. When I use strptime I get attribute error that datetime object doesn't apply to series object.

1

There are 1 answers

1
S_Crespo On

As the error message says, you can't apply strftime directly to a Series. Because a Series may have many dtypes, not only the datetype one. It's as if I wanted to apply .lower() to a float value: it makes no sense here.

So you need to spectify to pandas that you want to apply strftime to the values of the Series for which this function actually means something. In other terms:

Don't df.strftime('%H:%M:%s')
Do df.dt.strftime('%H:%M:%s') # the dt means "treat the content of the series as datetime objects"