-3

In python , i want to generate a random time between two intervals using randrange function and using the step parameter. I want the time to be generated at 5 minute intervals using randrange. Is it possible? Or is there any other function in python which can achieve the same?

import datetime
import time
import random

start = datetime.datetime(2017,4,25,8,0)
end = datetime.datetime(2017,4,25,11,30)
steptime = datetime.datetime(2017,4,25,0,5)
totalnum=10
start_ts = int(time.mktime(start.timetuple()))
end_ts = int(time.mktime(end.timetuple()))
step = int(time.mktime(steptime.timetuple()))
for val in range(totalnum):
    random_ts = random.randrange(start_ts, 
 end_ts,step)
RANDOMTIME = datetime.datetime.fromtimestamp(random_ts)
print(RANDOMTIME.strftime("%Y-%m-%d %H:%M"))

As mentioned above im not able to find a way to generate time within 5 minute intervals.

TIA

user2401464
  • 517
  • 2
  • 8
  • 20
  • Please mention reason for downvoting. As far as i know, i didnt violate any rules by asking the question. – user2401464 Apr 03 '18 at 11:02
  • I did't downvote. But it's a common reason for downvotes, Not saying what you have already tried or what you investigated before asking. Maybe that's the reason why they downvoted you (Not providing info to show that you already tried something) – jtagle Apr 03 '18 at 11:04
  • It was a simple question i didnt feel the need to provide the code. I have tried and will edit and post the same here. – user2401464 Apr 03 '18 at 11:07

3 Answers3

1

Thanks for the answers. I solved it by providing step as 300 seconds

random_ts = random.randrange(start_ts, end_ts,300)
user2401464
  • 517
  • 2
  • 8
  • 20
0

You can start by generating a random datetime between your start and end dates. See Generate a random date between two other dates

Then just round the random date to the nearest 5 minutes. See How to round the minute of a datetime object python

Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63
0

I think you're complicating this a bit too much - just subtact the earlier date from the later, get a random second (or millisecond if you want to go very granual) in its range and add it as a datetime.timedelta to the lower datetime, e.g.:

import datetime
import random

def datetime_in_range(low, high, interval):  # interval in seconds
    delta = (high - low).total_seconds()
    return low + datetime.timedelta(seconds=random.randrange(0, int(delta), interval))

# test
start = datetime.datetime(2017, 4, 25, 8, 0)
end = datetime.datetime(2017, 4, 25, 11, 30)

print(datetime_in_range(start, end, 300))  # 2017-04-25 09:25:00
print(datetime_in_range(start, end, 300))  # 2017-04-25 08:30:00
print(datetime_in_range(start, end, 300))  # 2017-04-25 11:10:00

If you want a millisecond precision, just multiply the delta with 1000 and use milliseconds in the datetime.timedelta() construct.

zwer
  • 24,943
  • 3
  • 48
  • 66