Generate A Random List Of N Dates In The Iso 8601 Format Within A Range In Python
Solution 1:
You can use random.sample
to sample without replacement or random.choices
to sample with replacement after generating a list of all the dates in the range.
If you don't want to store the list you could also generate N
random numbers from 1 through 365, then convert those to the appropriate dates.
import random
from datetime import date, timedelta
end_date =date(2019, 12, 31)
current_date=date(2019, 1, 1)
n =3
step = timedelta(days=1)
dates = [current_date]
while current_date!= end_date:
current_date+= step
dates.append(current_date)
random_dates = random.choices(dates, k=n)
print([d.isoformat() for d in random_dates])
Solution 2:
You can do something like this
import datetime
import random
# startdate
start_date = datetime.date(2019, 1, 1)
# enddate
end_date = datetime.date(2019, 12, 31)
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
#workload in days
random.seed(a=None)
random_number_of_days = random.randrange(days_between_dates)
random_date = start_date + datetime.timedelta(days=random_number_of_days)
print(str(random_date))
Which gave the following result when I ran it
2019-06-07
A similar question has been asked here Python - Generate random dates to create Gantt sequenced tasks?
Most of the code is from there except the last loop
Solution 3:
I create a dataframe with an datetimeindex with two iso8601 date values. I then resample the dataframe index to every 30Minute intervals then randomly choose 3 items from the dataframe.
df=pd.DataFrame({'timestamp':['2019-01-01T00:00:00.000Z','2019-12-31T23:59:59.300Z']})
df['timestamp']=df['timestamp'].apply(lambda timestamp: datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f%z'))
print(df['timestamp'])
df=df.set_index('timestamp')
dates = df.resample('30Min').max().dropna()
#print(dates)
random_dates = random.choices(dates.index, k=3)
print(random_dates)
output:
[Timestamp('2019-08-29 16:30:00+0000', tz='UTC', freq='30T'), Timestamp('2019-11-09 03:30:00+0000', tz='UTC', freq='30T'), Timestamp('2019-08-02 12:00:00+0000', tz='UTC', freq='30T')]
Post a Comment for "Generate A Random List Of N Dates In The Iso 8601 Format Within A Range In Python"