简体   繁体   English

将日期传递给列表

[英]Pass dates to a list

I'm attempting to generate random start and end dates with the end date being greater than the start date and pass the results to a list.我正在尝试生成结束日期大于开始日期的随机开始日期和结束日期,并将结果传递给列表。 I've tried a for loop but its not working as expected.我尝试了一个 for 循环,但它没有按预期工作。 Below is the code I'm using and the desired output I'm looking for.下面是我正在使用的代码和我正在寻找的所需 output。

"""Generate random dates where end date is greater than start date
   and append to list
"""
import random
from datetime import date

start = date(2019, 1, 1)
end = date(2019, 12, 31)

for i in range(27):
    random_start_date = start + (end - start) * random.random()
    random_end_date = random_start_date + (end - random_start_date) * random.random()
    #Converting to string in order to append to list
    start_dates = random_start_date.strftime('%Y-%m-%d')
    end_dates = random_end_date.strftime('%Y-%m-%d')
    print(start_dates, end_dates)


#Current output
2019-01-01 2019-02-01
2019-02-01 2019-03-01
2019-05-21 2019-05-31

#Desired output
[2019-01-01, 2019-02-01, 2019-05-21]
[2019-02-01, 2019-03-01, 2019-05-31]

You've got two problems there.你有两个问题。

The first is that you aren't appending to your list, you're replacing it, the second is you are printing every time through the loop rather than at the end.第一个是您没有附加到您的列表,您正在替换它,第二个是您每次都通过循环而不是最后打印。

Try this:尝试这个:

start_dates=[]
end_dates=[]
for i in range(27):
    random_start_date = start + (end - start) * random.random()
    random_end_date = random_start_date + (end - random_start_date) * random.random()
    #Converting to string in order to append to list
    start_dates.append(random_start_date.strftime('%Y-%m-%d'))
    end_dates.append(random_end_date.strftime('%Y-%m-%d'))
print(start_dates, end_dates, sep='\n')

(The sep='\n' puts each argument to print() on a new line.) sep='\n'print()的每个参数放在一个新行上。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM