Generate Random Timestamp in a given range?

2019-07-18 17:53发布

问题:

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!

回答1:

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)))