0

How to Generate random date of a particular month in this particular format.in order wise i.e., from 1 of month to 30 of that month

2011-08-12T20:17:46.384Z

Tried this but it generates in regular time date format. This code generates randomly but i need the values in order from 1 to 30/31 of that month

from datetime import datetime

d1 = datetime.strptime('1/1/2010 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2011 4:50 AM', '%m/%d/%Y %I:%M %p')

print(random_date(d1, d2))

1 Answers1

1

Perhaps you can get the difference in seconds between your datetimes then use random.randrange

from datetime import datetime, timedelta
import random

def random_date(d1, d2):
    delta = d2 - d1
    seconds = delta.total_seconds()
    n = random.randrange(seconds)
    return d1 + timedelta(seconds=n)

d1 = datetime.strptime('1/1/2010 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2011 4:50 AM', '%m/%d/%Y %I:%M %p')

print(random_date(d1, d2).isoformat(timespec='milliseconds')+'Z')
  • "Need in this format 2011-08-12T20:17:46.384Z" - then you should use the [strftime method of the datetime instance](https://docs.python.org/3/library/datetime.html#datetime.date.strftime) –  Oct 01 '19 at 04:02
  • Or just call the [isoformat method](https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat) as in my edited answer –  Oct 01 '19 at 04:10
  • format is right, but i need the values in order from 1 to 30/31 of that month –  Oct 01 '19 at 04:14