# Random dates (was RE: Why does this choke?)

Discussion in 'Python' started by Tim Peters, Nov 8, 2003.

1. ### Tim PetersGuest

There's some depressingly fiddly (low-level) code in this thread for
generating a number of random dates in a given year. Python 2.3 has a new
datetime module that makes mucking with dates easy, and a new
random.sample() function that makes finding a random subset easy. Combine
the two and you can get some lovely code for this task:

import datetime
import random

def days_in_year(y):
return datetime.date(y, 12, 31).timetuple().tm_yday

def n_random_dates_in_year(n, year, unique=True):
"""Generate n random dates in year.

Optional argument 'unique' (default True) controls whether
duplicate dates can be generated. By default, unique dates are
generated, and it's an error to specify n larger than the number
of days in the year. When unique is False, there's no limit on
how large n may be, or on how often a given date may be generated.
"""

diy = days_in_year(year)
start = datetime.date(year, 1, 1)
delta = datetime.timedelta

if unique:
if n > diy:
raise ValueError("year %d doesn't have %d unique days" %
(year, n))
for offset in random.sample(xrange(diy), n):
yield start + delta(days=offset)
else:
for dummy in xrange(n):
yield start + delta(days=random.randrange(diy))

Tim Peters, Nov 8, 2003