Python-指定时间段、随机生成指定数量日期
- 需求:在2021年3月1日-2021年6月30日之间,随机生成126个工作日日期。
思路:
1、生成规定范围内的日期列表
2、在1的列表中筛选出工作日,生成新列表
3、在2的基础上,随机抽取指定个数的日期
具体实现如下:
from chinese_calendar import is_workday
import random
import pandas as pd
# 在2021年3月1日-2021年6月30日之间的所有日期——range_calendar
range_calendar = pd.date_range('3/1/2021', '6/30/2021')
# 将上述日期中(range_calendar)中筛选出工作日,放到candidate列表中
candidate = []
for i in range(0, len(range_calendar)):
if is_workday(range_calendar[i]):
temp = Timestamp.date(range_calendar[i])
# 日期格式为:yyyymmdd
candidate.append(Timestamp.strftime(temp,"%Y%m%d"))
# 随机生成 constant_num = 126 个满足条件的日期,写到output.txt中(一行写一个日期,日期格式为:yyyymmdd)
constant_num = 126
file = open('output.txt','w')
# 循环选择随机日期constant_num次
for i in range(0,constant_num):
a_random_num = random.choice(result)
a_string_num = str(a_random_num)+'\n'
file.write(a_string_num)
file.close()
2021.7.30 更新:
方法与上述近似,修改为函数定义—主函数调用方式
import pandas as pd
from chinese_calendar import is_workday
import random
from pandas._libs.tslibs.timestamps import Timestamp
# Both arguments are strings. eg: '3/1/2021'-'month/day/year'
def select_workday(start,end):
result = []
date_range = pd.date_range(start,end)
num_of_date = len(date_range)
for i in range(0,num_of_date):
if is_workday(date_range[i]):
temp = Timestamp.date(date_range[i])
# 注释掉的方法,生成的格式为:20210730格式
# result.append(Timestamp.strftime(temp,"%Y%m%d"))
# 生成的格式为:2021-7-30
result.append(Timestamp.strftime(temp, "%Y-%m-%d"))
else:
continue
return result
# Generates a fixed number of out-of-order date files. file_name ——> 'output.txt', number ——> 126
def generate_ramdon_date_file(will_deal_list, number, file_name):
file = open(file_name,'w')
for i in range(0, number):
random_choice = random.choice(will_deal_list)
string_content = str(random_choice) + '\n'
file.write(string_content)
file.close()
print("Generate complete!")
# 随机取数方法不同--建议用这个
def generate_ramdon_date_file_2(will_deal_list, number, file_name):
file = open(file_name, 'w')
random_list = random.choices(will_deal_list,k = number)
for i in random_list:
string_content = str(i) + '\n'
file.write(string_content)
file.close()
print('finished!')
if __name__ == '__main__':
result = select_workday('3/1/2021', '6/30/2021')
# generate_ramdon_date_file(result,145,'output.txt')
generate_ramdon_date_file_2(result, 145, 'output.txt')