1

I have a list of dates. For each of these dates, keeping the month and year same, I need to generate a random date. I tried using this code:

def get_random_date(date):
    r_int = random.randint(1, 28)  #line 2
    rand_date = date[0:4] + date[5:7] + str(r_int)
    randm_date = datetime.datetime.strptime(rand_date, '%Y%m%d').date()
    return randm_date

But in this code I would never be getting 29, 30 or 31. If I remove the 28 in line 2 I might get 30 Feb or something like that. How to avoid this?

Edit: I do not need to get a random date b/w 2 dates. This is a different question. Plz let me know what other details I can provide to not get this marked duplicate.

John Holmes
  • 13
  • 1
  • 5
  • 1
    Possible duplicate of [Generate a random date between two other dates](https://stackoverflow.com/questions/553303/generate-a-random-date-between-two-other-dates) – Žilvinas Rudžionis Aug 23 '17 at 07:47

2 Answers2

1

In short, use calendar lib:

import calendar, random

def randomdate(year, month):
    dates = calendar.Calendar().itermonthdates(year, month)
    return random.choice([date for date in dates if date.month == month])

This function will return a datetime.date object.

In detail (TL;DR): dates is a iterator of all the dates in the weeks of that month. It includes several days from previous and next month. For example, list(calendar.Calendar().itermonthdates(2017, 8)) will also include 2017-07-31, 2017-09-01, 2017-09-02, 2017-09-03. So I used list comprehension to filter them out.


There is only one short hand: It cannot deal with dates between 1582-10-04 and 1582-10-15. Ten dates were skipped to make calendar correct. This is due to the python datetime lib.

InQβ
  • 518
  • 4
  • 22
0
from datetime import timedelta
from random import randrange
import calendar

def rnd_date(date):
    mrange = calendar.monthrange(date.year,date.month)
    d2 = date.replace(day=mrange[1])
    d1 = date.replace(day=mrange[0])
    delta = d2 - d1 
    result_int = delta.total_seconds()
    rnd = randrange(result_int)
    return d1 + timedelta(seconds=rnd)

Examples:

date = datetime.strptime('2/28/2020 1:30 PM', '%m/%d/%Y %I:%M %p')

rnd_date(date)
datetime.datetime(2020, 2, 10, 20, 37, 14)

day=0
rndate=None
while day != 29:
    rndate = rnd_date(date)
    day = rndate.day
day
29

rndate
datetime.datetime(2020, 2, 29, 9, 4, 41)
Sidon
  • 1,316
  • 2
  • 11
  • 26
  • I understand that this would help in getting a random date b/w 2 dates. I need to get a random date in the same month of the date that is passed in the function. – John Holmes Aug 23 '17 at 11:15
  • I am getting this Error - ValueError: day is out of range for month – John Holmes Aug 23 '17 at 12:03
  • Did you send a date to function, like my example? what date that generated the error? – Sidon Aug 23 '17 at 12:39