将两个字符串转换为时间戳(在您选择的分辨率,例如毫秒,秒,小时,天,无论什么),减去较早的时间戳,乘以您的随机数(假设它在范围[0,1]差异,并再次添加到较早的一个。将时间戳转换回日期字符串,并且在该范围内有随机时间。
Python示例(输出几乎是您指定的格式,除了0填充 – 归咎于美国时间格式约定):
import random
import time
def strTimeProp(start, end, format, prop):
"""Get a time at a proportion of a range of two formatted times.
start and end should be strings specifying times formated in the
given format (strftime-style), giving an interval [start, end].
prop specifies how a proportion of the interval to be taken after
start. The returned time will be in the specified format.
"""
stime = time.mktime(time.strptime(start, format))
etime = time.mktime(time.strptime(end, format))
ptime = stime + prop * (etime - stime)
return time.strftime(format, time.localtime(ptime))
def randomDate(start, end, prop):
return strTimeProp(start, end, '%m/%d/%Y %I:%M %p', prop)
print randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", random.random())