创建 x 个随机出生日期和 x 个在相应出生日期后至少 18 年的日期?

Creating x number of random date of births and x number of dates that are at least 18 years after corresponding date of birth?

我已经创建了一个随机出生日期列表,现在使用它我想创建一个随机开始日期列表,这些开始日期在 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())

这会创建一个包含 1000 个出生日期的列表,格式为 ['January 5 1974', ...],我想创建的第二个列表类似于 ['January 10, 1992' , ...]

我认为这对你有用:

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将包含您想要的日期列表。