'How to add timedelta for each time seperately contain in one column of data frame using pandas? [duplicate]

I have a dataframe like this:

action application_id interaction_time notification_id user_id
F 1 4489200 79 3152
F 1 4388400 79 3633
C 0 4410000 78 655
F 0 4489200 72 6280

which interaction_time is in seconds, now I want to add a column to dataframe which is interation time add to especific time(like: 2021,9,21).

I used this code:

seconds=df["interaction_time"]
df['date'] =  timedelta(seconds=df["interaction_time"]) + datetime.datetime(2019,6,1)

Finally I get this error:

unsupported type for timedelta seconds component: Series

how can I fixed it?



Solution 1:[1]

This works for me:

from datetime import datetime
import pandas as pd
df = pd.DataFrame({'action': ["F","F","C","F"],
                  'application_id': [1, 1,0,0],
                  'interaction_time': [4489200, 4388400,4410000,4489200],
                  'notification_id': [79, 79, 78, 72],
                  'user_id': [3152, 3633, 655, 6280]})

pd.to_timedelta(df['interaction_time'], unit='S') + datetime(2019,6,1)

Solution 2:[2]

Use:

s = """action   application_id  interaction_time    notification_id user_id
F   1   4489200 79  3152
F   1   4388400 79  3633
C   0   4410000 78  655
F   0   4489200 72  6280"""
temp = [x.split('   ') for x in s.split('\n')]
data = temp[1:]
cols = temp[0]
df = pd.DataFrame(data, columns = cols)
import datetime
base = datetime.datetime(2019,6,1)
pd.to_timedelta(df['interaction_time']+ ' S')+base

Output:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 le_camerone
Solution 2 keramat