2

I'm trying to do something like:

start=input("select starting date, format example : Jan 01 00:00:00")
end=input("select ending date")

if start>end:
     start,end=end,start

print(randomize_time(start,end))

Output:

>>> Aug 05 13:15:59

I have tried using random.randint, but if I select a range like: 00:00:00 && 01:00:00, the only part that is randomized is the hour, minutes and seconds will be ignored (since I'm doing random.randint(0,0)).

How would I do that properly?

Thanks in advance SO!

efotinis
  • 14,565
  • 6
  • 31
  • 36
windir
  • 21
  • 1
  • 3
  • You can convert the input to timestamp, and generate a random time between start and end, and then convert back to datetime – Dan Ionescu Feb 23 '17 at 12:58
  • can you paste the method body for randomize_time? You can pass the epoch time as parameters and them get a random timestamp and convert it back to a date string. – Nihal Sharma Feb 23 '17 at 12:59
  • The epoch thing rights perfectly. Thanks ;à – windir Feb 23 '17 at 13:08

1 Answers1

4

You can use something as below:

from random import randrange
import time

start_timestamp = time.mktime(time.strptime('Jun 1 2010  01:33:00', '%b %d %Y %I:%M:%S'))
end_timestamp = time.mktime(time.strptime('Jun 1 2017  12:33:00', '%b %d %Y %I:%M:%S'))

def randomize_time(start_timestamp,end_timestamp):
    return time.strftime('%b %d %Y %I:%M:%S', time.localtime(randrange(start_timestamp,end_timestamp)))