DEV Community

Discussion on: Python generate Birth date ( Quiz )

Collapse
 
agtoever profile image
agtoever

No need to use both time and datetime. I'd suggest to use a maximum age as input and a date format. You can leverage the functions of datetime to handle all the year/month/day separation of generation. This function can be expressed in two lines of code as:

from datetime import datetime, timedelta
from random import randint


def date_of_birth_generator(maximum_age=99, date_format="%Y-%m-%d", repeat=1):
    """ Generates date of births in the specified format and age range

    Args:
        maximum_age: the maximum age (relative to the current date)
        date_format: format of the date in Python datetime.strftime format
        repeat: the number of dates to generate
    """
    for _ in range(repeat):
        yield (
            datetime.today() - timedelta(days=randint(0, 365 * maximum_age))
        ).strftime(date_format)
Collapse
 
udomsak profile image
udomsak

Just knowing timedelta can do like this too. _)/