Create random time stamp list in python [closed]

2019-03-20 01:09发布

问题:

Is there a way to create a list of random irregular time stamps in strictly increasing format in Python? For example:

20/09/2013 13:00        
20/09/2013 13:01        
20/09/2013 13:05        
20/09/2013 13:09        
20/09/2013 13:16        
20/09/2013 13:26   

回答1:

You can build a random generator.

  • You can generate randrange(60) radom number between 0-60 (minutes)

  • use timedelta to add time to the actual date, in your case, it's 20/09/2013 13:..

  • build a generator random_date, with a starting date, and number of dates that you wanna generate.

from random import randrange
import datetime 


def random_date(start,l):
   current = start
   while l >= 0:
      curr = current + datetime.timedelta(minutes=randrange(60))
      yield curr
      l-=1



startDate = datetime.datetime(2013, 9, 20,13,00)

for x in random_date(startDate,10):
  print x.strftime("%d/%m/%y %H:%M")

Output:

20/09/13 13:12
20/09/13 13:02
20/09/13 13:50
20/09/13 13:13
20/09/13 13:56
20/09/13 13:40
20/09/13 13:10
20/09/13 13:35
20/09/13 13:37
20/09/13 13:45
20/09/13 13:27

UPDATE

You can trick that by adding the difference number to the last date that you have generated, then reverse the over-all list. You can also change the random number that you add everytime, to get the results that you want.

Your code would look like.

from random import randrange
import datetime 


def random_date(start,l):
   current = start
   while l >= 0:
    current = current + datetime.timedelta(minutes=randrange(10))
    yield current
    l-=1



startDate = datetime.datetime(2013, 9, 20,13,00)


for x in reversed(list(random_date(startDate,10))):
    print x.strftime("%d/%m/%y %H:%M")

Output:

20/09/13 13:45
20/09/13 13:36
20/09/13 13:29
20/09/13 13:25
20/09/13 13:20
20/09/13 13:19
20/09/13 13:16
20/09/13 13:16
20/09/13 13:07
20/09/13 13:03
20/09/13 13:01