DEV Community


Posted on

Python generate Birth date ( Quiz )

Today After end of work as Pizza Boy ( As delivery guy / call GrabBike. So i'm sitting front of my laptop found my follower in twitter talking about "function to Generate birth date" as quiz.

Then i try to solve this simple quiz with my self got it with 2 version one use of yield and second use more with lambda.

Version 1.

I use datetime function to limit current year then use random() with randrange method to get number from range that i limit it in range() function.

import random
from datetime import datetime

def genDateOfBirth(number=1):
    CurrentTime =
    Year = random.randrange(1911, CurrentTime.year)
    for item in range(number):
        yield random.randrange(1911,CurrentTime.year), random.randrange(1, 12), random.randrange(1, 31)

dateTimeThatIwant = genDateOfBirth(12)

for year, month, date in dateTimeThatIwant:
    print("GenDate in yyyy-mm-dd  as %s-%s-%s" % (year, month, date))

Version 2.

However, I have some question that

  • Can i refactor my code shorten ?.
  • Can i specify start year of computer usage that python use ?.

So got it use lambda and list-comprehension compound.

import random
from datetime import datetime
from time import gmtime

# gmtime(0) you will get epoch first year = 1970 
# read more -> 

startYear = gmtime(0)
CurrentYear =

dateTimeGeneratorList = lambda numberOflist : [(yield random.randrange(startYear.tm_year, currentYear.year), random.randrange(1,12), 
random.randrange(1,31)) for item in range(numberOflist)]

# 12 if number of list that we need to printout .

for year, month, date in dateTimeGeneratorList(12):
   print("%s-%s-%s " % (year, month, date))

Done!! But, Can i make it better ? :)

Top comments (2)

agtoever profile image

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

        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 (
   - timedelta(days=randint(0, 365 * maximum_age))
udomsak profile image

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