Generate random dates in python using datetime and random modules

In order to insert fake users into my database for test purposes (see the previous post), I forget to generate a random birth date but I’ve currently solved the problem using the two modules datetime and random:

from datetime import datetime
import random

year = random.choice(range(1950, 2001))
month = random.choice(range(1, 13))
day = random.choice(range(1, 29))
birth_date = datetime(year, month, day)

in practice I randomize the three parameters: year, month and day using choice(), which is a really cool method that returns a random element from a collection, collection that I dynamically created using range(). The code above create a random date bewteen January 1 1950 and December, 28 2000.

UPDATE:
as Jason has written in the comments, there is no need to use random.choice() + range(), since the random module provides a randint() method (which returns a random integer), so the code can be simplified in this way:

from datetime import datetime
import random

year = random.randint(1950, 2000)
month = random.randint(1, 12)
day = random.randint(1, 28)
birth_date = datetime(year, month, day)
  • Dan

    Thanks for the code. Just a heads up, if you want dates in December you’d want to use range(1, 13). Same for the day (you could go up to 28, so range(1, 29))

  • Yes, you are right… I fixed the code in the example, thanks ;)

  • Jason Green

    No need to use range at all:
    month = random.randint(1, 12)

  • Thanks Jason!

  • Sven

    Great example thanks! Do note that randint does include the largest number, so month should be randint(1, 12) as Jason suggested.

  • good catch, I’ve updated the code :)

  • Frawau

    I know it’s an old thread, but FWIW I would do

    startdate=dt.date(1950,1,1)
    nbdays=(dt.date.today()-startdate).days
    d=random.randint(0,nbdays)
    birth date=startdate+dt.timedelta(days=d)

    You don’t have to worry about how many days there are in a month or anything like that