How to add series values to date/datetime object?

Viewed 51

I have a pandas dataframe like as shown below

df = pd.DataFrame({'login_date':['5/7/2013 09:27:00 AM','09/08/2013 11:21:00 AM','06/06/2014 08:00:00 AM','06/06/2014 05:00:00 AM','','10/11/1990'],
'DURATION':[21,30,200,34,45,np.NaN})

I would like to add DURATION values to the login_date column

The DURATION is represented in Days type

If there is NA in DURATION column, just replace it with 0.

So, I tried the below

df['DURATION'] = df['DURATION'].fillna(0)
df['login_date'] = pd.to_datetime(df['login_date'])
df['DURATION'] = df['DURATION'].astype('Int64')
df['logout_Date'] = df['login_date'] + pd.offsets.DateOffset(days=df['DURATION'])

However, this results in an error as shown below

TypeError: Invalid type <class 'pandas.core.series.Series'>. Must be int or float.

But I have already converted my DURATION column to int64 type.

How to add a column of values to my logout_date column

1 Answers

Try:

df["logout_date"] = pd.to_datetime(df["login_date"]) + df["DURATION"].fillna(0).apply(lambda x: pd.Timedelta(days=x))
print(df)

Prints:

               login_date  DURATION         logout_date
0    5/7/2013 09:27:00 AM      21.0 2013-05-28 09:27:00
1  09/08/2013 11:21:00 AM      30.0 2013-10-08 11:21:00
2  06/06/2014 08:00:00 AM     200.0 2014-12-23 08:00:00
3  06/06/2014 05:00:00 AM      34.0 2014-07-10 05:00:00
4                              45.0                 NaT
5              10/11/1990       NaN 1990-10-11 00:00:00
Related