Harikrishna
Harikrishna

Reputation: 1140

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?

Upvotes: 11

Views: 21113

Answers (5)

Pasqo
Pasqo

Reputation: 3

To render removing "0 days" without converting to string:

>>> td_to_str = pd.Timedelta.__str__ 
>>> pd.Timedelta.__str__ = lambda x: td_to_str(x)[7:]

>>> pd.Timedelta(seconds=75)
Timedelta('0 days 00:01:15')

>>> str(pd.Timedelta(seconds=75))
'00:01:15'

Same thing can be done with repr for interactive use ...

Upvotes: 0

I found this method easy, others didnt work for me

df['column'] = df['column'].astype(str).map(lambda x: x[7:])

It slices of the days part and you only get time part

Upvotes: 3

Yaniv K.
Yaniv K.

Reputation: 286

I found a very easy solution for other people who may encounter this problem:

if timedelta_obj.days < 0:
    timedelta_obj.days = datetime.timedelta(
        seconds=timedelta_obj.total_seconds() + 3600*24)

Upvotes: 0

Asad Rauf
Asad Rauf

Reputation: 817

If your column is named time1, you can do it like this:

import pandas as pd
import datetime as dt
df['time1'] = pd.to_datetime(str(df.time1)[11:19]) #this slice can be adjusted
df['time1'] = df.time1.dt.time

this is going to convert the timedelta to str, slice the time part from it, convert it to datetime and extract the time from that.

Upvotes: 0

jezrael
jezrael

Reputation: 862481

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'>

Upvotes: 7

Related Questions