How to add time to a type datetime64

Question:

I have a dataframe which has a column named DEPARTURE. It is a datetime64 type that says the date and time of a departure. I also have a column named ACTUAL_ELAPSED_TIME which is the amount of minutes the flight took as an integer. I would like to create a new column named ARRIVAL which is the DEPARTURE + elapsed_time.

'''
for minutes in df.ACTUAL_ELAPSED_TIME:
    df.ARRIVAL = df.DEPARTURE + pd.Timedelta(minutes, unit='m')
'''

This seems to send it to an infinite loop.

Asked By: Fernando Araiza

||

Answers:

You don’t need a for loop. just:

df = pd.DataFrame({
    "DEPARTURE": pd.to_datetime(["2022-01-01 08:00", "2022-01-01 10:30"]),
    "ACTUAL_ELAPSED_TIME": [120, 180]
})
df["ARRIVAL"] = df["DEPARTURE"] + pd.to_timedelta(df["ACTUAL_ELAPSED_TIME"], unit="m")

print(df)

#            DEPARTURE  ACTUAL_ELAPSED_TIME             ARRIVAL
#0 2022-01-01 08:00:00                  120 2022-01-01 10:00:00
#1 2022-01-01 10:30:00                  180 2022-01-01 13:30:00
Answered By: BehRouz
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.