Remove the days in the timedelta object
Asked Answered
P

5

10

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?

Perch answered 3/11, 2018 at 9:18 Comment(1)
I think this answers your question.Smoker
H
7

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'>
Hydrometer answered 3/11, 2018 at 9:25 Comment(1)
The only one of the 2 solutions provided that worked was the string manipulation. The timedelta difference still shows 0 days and then the time differenceUnfriendly
T
2

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

Thermosetting answered 11/5, 2021 at 9:7 Comment(0)
I
0

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.

Inexpressive answered 3/11, 2018 at 9:58 Comment(0)
D
0

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)
Doings answered 13/2, 2019 at 8:45 Comment(0)
M
0

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

Mauretania answered 19/4 at 3:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.