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?
Remove the days in the timedelta object
I think this answers your question. –
Smoker
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'>
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 difference –
Unfriendly 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
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.
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)
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 ...
© 2022 - 2024 — McMap. All rights reserved.