Search code examples
pythontimesum

Sum datetime64[ns] Column and float64 Column


I'm trying to sum two columns: One is format float64 which are seconds and the other is format datetime64[ns]. They look like:

 time                  | float
---------------------------------
 2020-07-28 14:53:10   | 5.0
 2021-08-30 15:28:52   | 68.0
 2019-04-25 14:55:36   | 49.0
 2020-03-24 09:19:45   | 8.0
 2021-02-10 07:44:26   | 6.0

I performed the sum as follows:

df['time'] + df['float']

I then received the following message:

ufunc 'add' cannot use operands with types dtype('<M8[ns]') and dtype('float64')

I tried to convert the float column to timedate and then perform the sum and I received the following message:

unsupported operand type(s) for +: 'Timestamp' and 'Timestamp'`


Solution

  • Convert the "float" column to pd.Timedelta using pd.to_timedelta and then sum:

    df["time"] = pd.to_datetime(df["time"])
    df["float"] = pd.to_timedelta(df["float"], unit="D") #change units if needed
    
    >>> df.sum(axis=1)
    0   2020-08-02 14:53:10
    1   2021-11-06 15:28:52
    2   2019-06-13 14:55:36
    3   2020-04-01 09:19:45
    4   2021-02-16 07:44:26
    dtype: datetime64[ns]