Generate two df columns with random datetime values – max difference of +5 days

Question:

I have df containing randomly created dates in the current year.

df['timestamp_open'] = [randomtimestamp(start_year=2023,end_year=2023) for _ in range(len(df.index))]

I would need additional datetime column whose values are randomly higher, but not more than 5 days.
Don’t know how to do it

Edit: adding a fragment of df containing randomly created datetime, as per comment:

df fragment

Answers:

You can add random amount of minutes (or seconds, whatever you’d like) using TimeDelta. Consider the following example:

from random import randint
from pandas import Timedelta

df = pd.DataFrame({"date": pd.date_range("2023-01-01", "2023-10-01", 10)})
df['rand_add_date'] = df.apply(lambda r: r['date'] + Timedelta(randint(1,5*24*60), unit='minutes'), axis=1)
print(df)
#                  date       rand_add_date
# 0 2023-01-01 00:00:00 2023-01-01 14:33:00
# 1 2023-01-31 08:00:00 2023-02-02 16:08:00
# 2 2023-03-02 16:00:00 2023-03-05 10:42:00
# 3 2023-04-02 00:00:00 2023-04-03 00:53:00
# 4 2023-05-02 08:00:00 2023-05-05 12:29:00
# 5 2023-06-01 16:00:00 2023-06-04 14:51:00
# 6 2023-07-02 00:00:00 2023-07-02 23:58:00
# 7 2023-08-01 08:00:00 2023-08-03 15:45:00
# 8 2023-08-31 16:00:00 2023-09-04 03:55:00
# 9 2023-10-01 00:00:00 2023-10-01 03:41:00
Answered By: JarroVGIT
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.