I want to sum two pandas Series.
The first series is a hh:mm time value; the second series contains Timedelta objects obtained from pd.Timedelta
.
The expected result is a hh:mm time regardless of day change (e.g. 22:00 + 4 hours = 02:00).
I created the Delta series like this:
delta = pd.Series(0 for x in range(0, len(df.Time_In_Hours)))
for j in range(0, len(df.Time_In_Hours)):
delta[j] = pd.Timedelta(df.Time_In_Hours[j], 'h')
df = df.assign(Delta = delta)
print ("Delta dtype = %s" % (df.Delta.dtype))
print ("Start_Time dtype = %s" % (df.Start_Time.dtype))
#Output
Delta dtype = object
Start_Time dtype = object
What I tried:
df["end_Time"] = df["Start_Time"] + df["Delta"]
The error I am receiving is:
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'Timedelta'
How can I sum these two series ?
The error is pretty clear. If you check the types of the elements, you will find out that at some point you are tying to add datetime.time
object and pandas.Timedelta
.
There are 2 kinds of dates, times and timedeltas:
datetime
module i.e. datetime.time
, datetime.date
, datetime.timedelta
, ...pandas.Timestamp
, pandas.Timedelta
these two stacks are incompatible for basic operations as addition or comparison.
Convert everything to pandas type and extract the times in the end
You should make sure, that dtypes
of your columns are something like datetime64[ns]
and timedelta64[ns]
. For that, try converting them explicitly using pd.to_datetime
and pd.to_timedelta
.
Another approach would be just converting the Delta
column to datetime.timedelta
you could try
df["end_Time"] = df["Start_Time"] + df["Delta"].map(pd.Timedelta.to_pytimedelta)
But you may run into some more errors depending on what is in your df["Delta"]
and df["Start_Time"]