我已经创建了一个随机的出生日期列表,现在我想使用它来创建一个随机的起始日期列表,这些起始日期在1980年1月1日之后,并且至少在出生日期之后18年。
我能够生成随机的出生日期,但是我不确定如何使用这些日期来生成1980年1月1日之后和至少18岁之后的开始日期。
birthdates = []
import time
def strTimeProp(start, end, format, prop):
"""Get a time at a proportion of a range of two formatted times.
start and end should be strings specifying times formated in the
given format (strftime-style), giving an interval [start, end].
prop specifies how a proportion of the interval to be taken after
start. The returned time will be in the specified format.
"""
stime = time.mktime(time.strptime(start, format))
etime = time.mktime(time.strptime(end, format))
ptime = stime + prop * (etime - stime)
return time.strftime(format, time.localtime(ptime))
def randomDate(start, end, prop):
birthdates.append(strTimeProp(start, end, '%B %d %Y', prop))
for n in range(1000):
randomDate("January 1 1960", "June 1 2001", random.random())
这将以['January 5 1974',...]的格式创建1000个出生日期的列表,我要创建的第二个列表是类似['January 10,1992', ...]
答案 0 :(得分:1)
我认为这对您有用:
birthdates = []
import time
import random
def strTimeProp(start, end, format, prop):
"""Get a time at a proportion of a range of two formatted times.
start and end should be strings specifying times formated in the
given format (strftime-style), giving an interval [start, end].
prop specifies how a proportion of the interval to be taken after
start. The returned time will be in the specified format.
"""
if len(start) == 6:
start = '0' + start[0] + '0' + start[1:]
elif len(start) == 7:
start = '0' + start
try:
stime = time.mktime(time.strptime(start, format))
except:
year = start[:-4]
stime = time.mktime(time.strptime("February 28 " + year, format))
etime = time.mktime(time.strptime(end, format))
ptime = stime + prop * (etime - stime)
return time.strftime(format, time.localtime(ptime))
def randomDate(start, end, prop, list):
list.append(strTimeProp(start, end, '%B %d %Y', prop))
for n in range(1000):
randomDate("January 1 1960", "June 1 2001", random.random(), birthdates)
later_dates = []
for date in birthdates:
month_day = date[:-4]
year = date[-4:]
randomDate(month_day + str(int(year) + 18), "June 1 2019", random.random(), later_dates)
列表later_dates
将包含您想要的日期的列表。