Search code examples
pythonpandasminutedatetime64

How to add minutes to datetime64 object in a Pandas Dataframe


I want to add a list of minutes to datetime64 columns into a new df column.

I tried using datetime.timedelta(minutes=x) in a for loop. But as a result, it is adding a constant value to all of my rows. How do I resolve this?

for x in wait_min:
    data['New_datetime'] = data['Date'] + datetime.timedelta(minutes=x)

I expect to iterate through the list and add corresponding minutes, but this is adding a constant value of 16 minutes to each row.


Solution

  • pandas sums two Series element-wise, if they have the same length. All you need to do is create a Series of timedelta objects.

    So if wait_min is a list of minutes of length equal to the number of rows in your dataframe, this will do:

    data['New_datetime'] = data['Date'] + pd.Series([datetime.timedelta(minutes=x) for x in wait_min])