Ravindra
Ravindra

Reputation: 41

How to add random offset to each date column of dataframe

I want to add random offset to each date column of dataframe.

`df['date_offset'] = np.random.randint(1, 100, df.shape[0])

df['from_date'] = datetime.datetime.now()
df['to_date'] = df['from_date'] + datetime.timedelta(days=df['date_offset'])`

But it's giving error as expected.

TypeError: unsupported type for timedelta days component: Series

Can anyone please help me with this.

Upvotes: 1

Views: 138

Answers (1)

jezrael
jezrael

Reputation: 862511

Use to_timedelta:

df['to_date'] = df['from_date'] + pd.to_timedelta(df['date_offset'], unit='d')
#df['to_date'] = datetime.datetime.now() + pd.to_timedelta(df['date_offset'], unit='d')

If need add random days without times use:

 a = np.random.randint(1, 100, df.shape[0])
 df['to_date'] = pd.Timestamp.now().normalize() + pd.to_timedelta(a, unit='d')

Or:

df['to_date'] = pd.to_datetime(a, unit='d', origin=datetime.datetime.now())

Upvotes: 1

Related Questions