Python 获取时间段内的随机时间(list)、时间戳(list)

获取两个时间点间的随机时间&时间戳

方案一

# python2 不兼容,python3正常
import datetime,random
def randomtimes(start, end, n, frmt="%Y-%m-%d"):
    stime = datetime.datetime.strptime(start, frmt)
    etime = datetime.datetime.strptime(end, frmt)
    return [random.random() * (etime - stime) + stime for _ in range(n)]

randomtimes('2018-06-01','2018-11-01',10)

方案二

import random
import time
from datetime import datetime

def strTimeProp(start, end, prop, frmt):
    stime = time.mktime(time.strptime(start, frmt))
    etime = time.mktime(time.strptime(end, frmt))
    ptime = stime + prop * (etime - stime)
    return int(ptime)

def randomTimestamp(start, end, frmt='%Y-%m-%d %H:%M:%S'):
    return strTimeProp(start, end, random.random(), frmt)

def randomDate(start, end, frmt='%Y-%m-%d %H:%M:%S'):
    return time.strftime(frmt, time.localtime(strTimeProp(start, end, random.random(), frmt)))

def randomTimestampList(start, end, n, frmt='%Y-%m-%d %H:%M:%S'):
    return [randomTimestamp(start, end, frmt) for _ in xrange(n)]

def randomDateList(start, end, n, frmt='%Y-%m-%d %H:%M:%S'):
    return [randomDate(start, end, frmt) for _ in xrange(n)]

start = '2018-06-02 12:12:12'
end = '2018-11-01 00:00:00'
lenth = 10
print(randomTimestamp(start, end))
print(randomDate(start,end))
print(randomTimestampList(start, end, lenth))
print(randomDateList(start, end, lenth))

结果

Python 获取时间段内的随机时间(list)、时间戳(list)_第1张图片

你可能感兴趣的:(Python,Pythonic,Tips)