问题描述
这个想法是基于 Python 中的工作量估计生成随机但有序的日期.
The idea is to generate random but sequenced dates based on workload estimation in python.
目标是有这样的输出:
任务、开始日期、结束日期
任务 1, 01/06/2020, 05/06/2020
任务 2, 08/06/2020, 11/06/2020
任务 3、12/06/2020、24/06/2020
...
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)
知道如何随机化吗?
推荐答案
你需要一个种子:
random.seed(a=None)
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.
你可以这样做:
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.
您可以制作一个开始日期列表,然后用 i 将它们编入索引.这将允许您为每个任务指定一个特定的开始日期.
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.
这篇关于Python - 生成随机日期以创建甘特排序任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!