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 = datetime.now()
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 -> https://en.wikipedia.org/wiki/System_time
startYear = gmtime(0)
CurrentYear = datetime.now()
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))
Top comments (2)
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:
Just knowing timedelta can do like this too. _)/