在python中创建随机时间戳列表 [英] Create random time stamp list in python

查看:482
本文介绍了在python中创建随机时间戳列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在Python中以严格增加的格式创建随机不规则时间戳的列表?例如:

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   

推荐答案

您可以构建随机生成器.

You can build a random generator.

  • 您可以在0-60(分钟)之间生成randrange(60)随机数

使用timedelta将时间添加到实际日期中,在您的情况下为20/09/2013 13:..

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

构建一个生成器random_date,其中包含开始日期和您要生成的日期数.

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

输出:

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

更新

您可以通过将差异编号添加到生成的最后日期来欺骗,然后反转总体列表. 您还可以更改每次添加的随机数,以获得所需的结果.

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

输出:

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

这篇关于在python中创建随机时间戳列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆