我需要在python
中生成一对随机日期作为时间间隔从2017年1月1日至6月2日或2018年5月4日至9月9日
我用这个来生成随机日期:
now = firstJan + timedelta(days = random.randint(0, 365 if calendar.isleap(firstJan.year) else 364))
如何生成随机间隔?
答案 0 :(得分:2)
我是这样做的 -
import datetime, random, calendar
# Function to get random date with given month & year
def getDate(m, y, start=1):
# For months havin 30 days
if m in [4,6,9,11]:
return random.randrange(start,30,1)
# For month of Feb, to check if year is leap or not
elif m == 2:
if not calendar.isleap(y):
return random.randrange(start,28,1)
else:
return random.randrange(start,29,1)
else:
return random.randrange(start,31,1)
# Function to return random time period
def getRandomPeriod(minYear, maxYear):
if minYear > maxYear:
raise ValueError('Please enter proper year range')
if minYear == maxYear:
y1 = minYear
y2 = minYear
else:
y1 = random.randrange(minYear, maxYear)
# Choosing lower bound y2 to be same as y1, so that y2 >= y1
y2 = random.randrange(y1, maxYear)
m1 = random.randrange(1,12)
if y2 != y1:
m2 = random.randrange(1,12,1)
else:
# Choosing lower bound m2 to be same as m1, so that m2 >= m1
m2 = random.randrange(m1,12,1)
d1 = getDate(m1, y1)
if m1==m2 and y1==y2:
d2 = getDate(m2, y2, start=d1+1)
else:
d2 = getDate(m2, y2)
t1 = datetime.datetime(y1,m1,d1)
t2 = datetime.datetime(y2,m2,d2)
return (t1.strftime('%B %d %Y'), t2.strftime('%B %d %Y'))
getRandomPeriod(2010,2010)
=> ('January 03 2010', 'October 09 2010')
getRandomPeriod(2010,2012)
=> ('July 07 2011', 'August 06 2011')