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

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

  1. Tim Peters

    Tim Peters Guest

    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
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. David Lozzi

    Dates dates dates dates... SQL and ASP.NET

    David Lozzi, Sep 29, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    867
    Rob Schieber
    Sep 30, 2005
  2. S Kemplay

    Why does this choke?

    S Kemplay, Nov 7, 2003, in forum: Python
    Replies:
    4
    Views:
    384
    Dennis Lee Bieber
    Nov 9, 2003
  3. S Kemplay

    Why does this choke?

    S Kemplay, Nov 7, 2003, in forum: Python
    Replies:
    2
    Views:
    310
    S Kemplay
    Nov 7, 2003
  4. Mr. SweatyFinger
    Replies:
    2
    Views:
    1,963
    Smokey Grindel
    Dec 2, 2006
  5. Z. M. Wu

    why does Perl choke here?

    Z. M. Wu, Nov 24, 2003, in forum: Perl Misc
    Replies:
    1
    Views:
    107
    Gunnar Hjalmarsson
    Nov 24, 2003
Loading...

Share This Page