2

I need to generate a random pair of dates as a time interval in python

Like from January 1 to June 2 2017 or from May 4 to September 9 2018

I'm using this to generate a random date:

now = firstJan + timedelta(days = random.randint(0, 365 if calendar.isleap(firstJan.year) else 364))

How do I generate a random interval?

1
  • What kind of distribution do you expect your date ranges to have? Should every day be equally likely to fall in the range? Or should each day be equally likely to be one of the end points of the range? Those are different! An obvious (and simple) solution would be to use the date you generate with your code above as the start date, and then pick a length for the range and add that many days to get the end date. But there are lots of other ways, and you haven't given us any good way to tell which is best for you. Commented May 22, 2017 at 13:12

1 Answer 1

2

Here's how I did it -

import datetime, random, calendar

# Function to get random date with given month & year
def getDate(m, y, start=1):
    # For months havin 30 days
    if m in [4,6,9,11]: 
        return random.randrange(start,30,1)
    # For month of Feb, to check if year is leap or not
    elif m == 2:
        if not calendar.isleap(y):
           return random.randrange(start,28,1)
        else:
           return random.randrange(start,29,1)
    else:
           return random.randrange(start,31,1)

# Function to return random time period
def getRandomPeriod(minYear, maxYear):
    if minYear > maxYear:
        raise ValueError('Please enter proper year range')
    if minYear == maxYear:
        y1 = minYear
        y2 = minYear
    else:
        y1 = random.randrange(minYear, maxYear)
        # Choosing lower bound y2 to be same as y1, so that y2 >= y1
        y2 = random.randrange(y1, maxYear)

    m1 = random.randrange(1,12)
    if y2 != y1:
        m2 = random.randrange(1,12,1)
    else:
        # Choosing lower bound m2 to be same as m1, so that m2 >= m1
        m2 = random.randrange(m1,12,1)

    d1 = getDate(m1, y1)
    if m1==m2 and y1==y2:
        d2 = getDate(m2, y2, start=d1+1)
    else:
        d2 = getDate(m2, y2)

    t1 = datetime.datetime(y1,m1,d1)
    t2 = datetime.datetime(y2,m2,d2)
    return (t1.strftime('%B %d %Y'), t2.strftime('%B %d %Y'))

 getRandomPeriod(2010,2010)
 => ('January 03 2010', 'October 09 2010')

 getRandomPeriod(2010,2012)
 => ('July 07 2011', 'August 06 2011')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.