Skip to content
Advertisement

Datetime object in DataFrame with just time

This is the plain column

0       06:55:22
1       06:55:23
2       06:55:24
3       06:55:25
4       06:55:26

And the I would like to put that column in the index, the problem is when I try to use the method resample() I always get the same problem:

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of ‘Index’

I’ve been using this to change the Time column to

datetime dt['Time'] = pd.to_datetime(dt['Time'],format).apply(lambda x: x.time())

Advertisement

Answer

You can use set_index to set the Time column as your index of the dataframe.

In [1954]: df.set_index('Time')                                                                                                                                                                             
Out[1954]: 
          a
Time       
06:55:23  1
06:55:24  2
06:55:25  3
06:55:26  4

Update after OP’s comment

If you don’t have a date column, so pandas will attach a default date 1900-01-01 when you convert it to datetime. Like this:

In [1985]: pd.to_datetime(df['Time'], format='%H:%M:%S')                                                                                                                                                    
Out[1985]: 
0   1900-01-01 06:55:23
1   1900-01-01 06:55:24
2   1900-01-01 06:55:25
3   1900-01-01 06:55:26
Name: Time, dtype: datetime64[ns]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement