Python - Generate random dates to create Gantt sequenced tasks

我是研究僧i 提交于 2021-02-04 21:01:06

问题


The idea is to generate random but sequenced dates based on workload estimation in python.

The goal is to have an output like this:

Task, Start_date, End_date
task1, 01/06/2020, 05/06/2020
task2, 08/06/2020, 11/06/2020
task3, 12/06/2020, 24/06/2020
...

So I started to work on this code but unable to find a way to randomize it.

#startdate
start_date = datetime.date(2020, 1, 1)
#enddate
end_date = datetime.date(2020, 2, 1)
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
#workload in days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_date + datetime.timedelta(days=random_number_of_days)

Any idea on how to randomize?


回答1:


You need a seed:

random.seed(a=None)

a is the seed value. If it is None then the system time is used by default. Add this line before you start generating random dates. Don't set the seed inside a loop because that causes bugs.

You can do something like this:

import datetime
import random
# startdate
start_date = datetime.date(2020, 1, 1)
# enddate
end_date = datetime.date(2020, 2, 1)
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
#workload in days

random.seed(a=None)

tasks = 10

for i in range(tasks):
    random_number_of_days = random.randrange(days_between_dates)
    random_date = start_date + datetime.timedelta(days=random_number_of_days)
    print("Task" + str(i+1) + "," + str(start_date) + "," + str(random_date))
    start_date = random_date # by @Makram

You will need to change what start date is, too, unless you want all of them to start at the same date.

You can make a list of startdates and then index them with i. This will allow you to have a specific start date for each of the tasks.



来源:https://stackoverflow.com/questions/62140629/python-generate-random-dates-to-create-gantt-sequenced-tasks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!