在此处输入代码我是新手,我想在python中生成日期/日期以帮助我的同事。在这里,我们假设星期日和星期六为周末,为什么我的函数有时会返回无?我想每次运行时都经过固定的年份和月份,例如,只需运行a = RandomWeekdays(2018,6)即可获得日期,是否有解决方案?
import calendar
import datetime
import random
import re
def RandomWeekdays(year,month):
def randomdate(year, month):
dates = calendar.Calendar().itermonthdates(year, month)
return random.choice([date for date in dates if date.month == month])
RandomDate_R = randomdate(2018, 6)
RandomDateStr_R = RandomDate_R.strftime('%Y-%m-%d')
date_num_iter = re.findall(r'\d{1,2}',RandomDateStr_R)
day = int(date_num_iter[3])
dayOrder = calendar.weekday(2018,month,day)
if dayOrder in range(0,5):
return day
else:
day+=2`enter code here`
if day > 29:
day-=4
return day
a=RandomWeekdays(2018,6)
print(a)
答案 0 :(得分:2)
您将得到None
,因为您尚未使用if
处理相应的条件,可以为else
写入if
来添加句柄代码。
但是我建议您使用熊猫轻松实现它。
import random, calendar
import pandas as pd
def randomDate(year, month):
day_count = calendar.monthrange(year, month)[1]
t = random.choice(pd.date_range(f"{year}-{month}-01", f"{year}-{month}-{day_count}", freq='D'))
return randomDate() if t.dayofweek == 5 or t.dayofweek == 6 else t
randomDate(2018, 8)
# Timestamp('2018-08-20 00:00:00', freq='D')