pythonpandasdatetimetimedelta

Remove the days in the timedelta object


I have a column in a pandas dataframe that is created after subtracting two times. I now have a timedelta object like this -1 days +02:45:00. I just need to remove the -1 days and want it to be 02:45:00. Is there a way to do this?


Solution

  • I think you can subtract days converted to timedeltas:

    td = pd.to_timedelta(['-1 days +02:45:00','1 days +02:45:00','0 days +02:45:00'])
    df = pd.DataFrame({'td': td})
    
    df['td'] = df['td'] - pd.to_timedelta(df['td'].dt.days, unit='d')
    
    print (df.head())
    
            td
    0 02:45:00
    1 02:45:00
    2 02:45:00
    
    print (type(df.loc[0, 'td']))
    <class 'pandas._libs.tslibs.timedeltas.Timedelta'>
    

    Or convert timedeltas to strings and extract strings between days and .:

    df['td'] = df['td'].astype(str).str.extract('days (.*?)\.')
    print (df.head())
              td
    0  +02:45:00
    1   02:45:00
    2   02:45:00
    
    print (type(df.loc[0, 'td']))
    <class 'str'>