Code to generate a random date of birth which will always represent an age less than 18 years from current date I want to generate a random date of birth [mm/dd/yyyy]which will
represent an age equal to less than 18years old
My requirement is to dynamically generate test data [date of birth]
to negatively test a system which needs a date of birth (age) to be
always greater than 18 years old
The system which I am trying to test compares the user's input
D.O.B. with the current date and calculates the age, if the age is
less than 18 years old then throws an error
I have tried to create the below python snippet to generate a date
of birth [for age less than 18 years old] and kindly need expert opinions to know if this
is indeed the correct/best approach?

start_date = date.today() - relativedelta(years=18)
end_date = date.today()
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_date + datetime.timedelta(days=random_number_of_days)
month = random_date.month
day = random_date.day
year = random_date.year
# Once I have the the day, month, year then I can convert it in ISO date format as per my needs
datetime.date has a .replace() method that returns a copy with some values changed.  This can be used to get the date 18 years ago.
end_date = date.today()
start_date = end_date.replace(year=end_date.year - 18)

datetime.date.toordinal returns an integer corresponding to the date. The ordinals for the start and stop date can be used in random.randint() to pick a random ordinal, which can then be converted back into a date with date.fromordinal().
random_date = date.fromordinal(random.randint(start_date.toordinal(), end_date.toordinal()))

date.isoformat() returns a date a as YYYY-MM-DD. Or use date.strftime() for more control over the date format.  In an f-string, a date is converted to ISO format, or a format string can be used:  f&quot;{random_date:%a, %b %d, %Y}&quot; -&gt; 'Sat, Dec 14, 2013'.
If you want to generate a list of dates in the range, use random.sample() with a range object.
NUMBER_OF_DATES = 10

date_range = range(start_date.toordinal(), end_date.toordinal())
random_dates = [date.fromordinal(o) for o in random.sample(date_range, NUMBER_OF_DATES)]