Home > Mobile >  Remove the days in Timedelta column
Remove the days in Timedelta column

Time:12-31

This is a column in my data frame and I want to remove the 0 days so the column will just show the time

           Time
0     0 days 04:00:00
1     0 days 04:01:00
2     0 days 04:03:00
3     0 days 04:04:00
4     0 days 04:07:00

Desired output:

         Time
0      04:00:00
1      04:01:00
2      04:03:00
3      04:04:00
4      04:07:00

I've been recommended this question > Link

And tried to suit it to my code with this code:

df['Time'] = df['Time'] - pd.to_timedelta(df['Time'].dt.days, unit='d')

But I'm still getting the same output:

           Time
0     0 days 04:00:00
1     0 days 04:01:00
2     0 days 04:03:00
3     0 days 04:04:00
4     0 days 04:07:00

CodePudding user response:

If you don't care about the time-intelligence of dtype: timedelta64[ns] you can cast it to string and remove the '0 days ' part:

df.Time.astype(str).str.replace('0 days ', '')

Update

In case the Time column is not always '0 days', you can remove the days with the following code:

df['Time'] = df['Time'] - pd.to_timedelta(df['Time'].dt.days, unit='d')

CodePudding user response:

Try with

df['Time'].astype(str).str.split(' ').str[-1]
Out[288]: 
0    04:00:00
1    04:01:00
2    04:03:00
3    04:07:00
Name: Time, dtype: object
  • Related