在Python范围内以iso 8601格式生成n个日期的随机列表 [英] Generate a random list of n dates in the iso 8601 format within a range in Python

查看:49
本文介绍了在Python范围内以iso 8601格式生成n个日期的随机列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个iso8601格式的日期随机列表,范围为2019-01-01至2019-12-31 n次.

I want to generate a random list of dates in the iso8601 format within the range from 2019-01-01 to 2019-12-31 n times.

from datetime import date
start_date = date(2019,1,1)
end_date = date(2019,12,31)

我看过的其他线程仅给出该范围内所有日期的列表,但这不是我所需要的.我还需要将日期设置为iso8601格式.实现此目标的最佳方法是什么?

Other threads I've looked at simply give the list of all dates within that range, but that's not what I need. I also need the dates to be in the iso8601 format. What is the best way to achieve this?

推荐答案

在替换后,您可以使用 random.sample 进行采样,或者在替换后使用 random.choices 进行替换生成该范围内所有日期的列表.

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.

如果您不想存储列表,还可以生成1到365之间的 N 个随机数,然后将其转换为适当的日期.

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])

这篇关于在Python范围内以iso 8601格式生成n个日期的随机列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆